首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ValueError:无效的RGBA参数: nan

ValueError:无效的RGBA参数: nan
EN

Stack Overflow用户
提问于 2021-10-05 19:57:00
回答 1查看 130关注 0票数 0

当我试图绘制一个包含1000个节点的图时,我遇到了一个错误。原因似乎是因为

事实上,我可以在映射器中看到一些NaN值:

代码语言:javascript
复制
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xsize, get_next_color_func)
   4290             try:  # Is 'c' acceptable as PathCollection facecolors?
-> 4291                 colors = mcolors.to_rgba_array(c)
   4292             except (TypeError, ValueError) as err:

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/colors.py in to_rgba_array(c, alpha)
    340     else:
--> 341         return np.array([to_rgba(cc, alpha) for cc in c])
    342 

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/colors.py in <listcomp>(.0)
    340     else:
--> 341         return np.array([to_rgba(cc, alpha) for cc in c])
    342 

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/colors.py in to_rgba(c, alpha)
    188     if rgba is None:  # Suppress exception chaining of cache lookup failure.
--> 189         rgba = _to_rgba_no_colorcycle(c, alpha)
    190         try:

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/colors.py in _to_rgba_no_colorcycle(c, alpha)
    262     if not np.iterable(c):
--> 263         raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
    264     if len(c) not in [3, 4]:

ValueError: Invalid RGBA argument: nan

然后

代码语言:javascript
复制
ValueError: 'c' argument must be a color, a sequence of colors, or a sequence of numbers, not dict_values(['#0010ff', '#40ffb7', '#00a4ff', '#40ffb7', '#00a4ff', '#40ffb7', '#ffb900', '#0010ff', nan, '#000080', '#000080', '#000080', '#000080', nan, '#0010ff', '#0010ff', '#800000', '#0010ff', '#0010ff', '#ff3000', '#0010ff', nan, '#00a4ff', '#0010ff', '#0010ff', '#ff3000', nan, nan, '#000080', '#0010ff', '#0010ff', '#0010ff', nan, nan, '#0010ff', nan, nan, '#0010ff', '#0010ff', nan, '#40ffb7', '#00a4ff', '#00a4ff', '#00a4ff', '#0010ff', '#0010ff', '#0010ff', nan, '#800000', nan])

代码(来自ValueError due to a missing element in color map)。请注意,下面的代码可以工作,但当我扩展node>500的数量时,出现了上面的错误:

代码语言:javascript
复制
import networkx as nx
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt, colors as mcolor

# Sample DataFrames
df1 = pd.DataFrame({
    'Node': ['A', 'A', 'B', 'B', 'B', 'Z'],
    'Edge': ['B', 'D', 'N', 'A', 'X', 'C']
})
df2 = pd.DataFrame({
    'Nodes': ['A', 'B', 'C', 'D', 'N', 'S', 'X'],
    'Attribute': [-1, 0, -1.5, 1, 1, 9, 0]
})

# Simplified construction of `colour_map`
uni_val = df2['Attribute'].unique()
colors = plt.cm.jet(np.linspace(0, 1, len(uni_val)))
# Map colours to_hex then zip with
mapper = dict(zip(uni_val, map(mcolor.to_hex, colors)))

G = nx.from_pandas_edgelist(df1, source='Node', target='Edge')
# Create Colour map. Ensure all nodes have a value via reindex
color_map = (
    df2.set_index('Nodes')['Attribute'].map(mapper)
        .reindex(G.nodes(), fill_value='black')
)
# Add Attribute to each node
nx.set_node_attributes(G, color_map, name="colour")

# Then draw with colours based on attribute values:
nx.draw(G,
        node_color=nx.get_node_attributes(G, 'colour').values(),
        with_labels=True)

plt.show()

我不知道如何在NaN值的情况下使用if条件来避免ValueError消息,并正确地将节点与其颜色相关联。我希望你能提供一些帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-06 11:55:28

即使有1000个节点,你的代码也适用于我,试着运行以下代码:

代码语言:javascript
复制
    import networkx as nx
    import numpy as np
    import pandas as pd
    from matplotlib import pyplot as plt, colors as mcolor

    G = nx.fast_gnp_random_graph(1000,0.05)
    df2 = pd.DataFrame({
        'Nodes': [i for i in G.nodes()],
        'Attribute': [np.random.rand()*9 for i in G.nodes()]
    })
    # Simplified construction of `colour_map`
    uni_val = df2['Attribute'].unique()
    colors = plt.cm.jet(np.linspace(0, 1, len(uni_val)))
    # Map colours to_hex then zip with
    mapper = dict(zip(uni_val, map(mcolor.to_hex, colors)))

    # Create Colour map. Ensure all nodes have a value via reindex
    color_map = (
        df2.set_index('Nodes')['Attribute'].map(mapper)
            .reindex(G.nodes(), fill_value='black')
    )
    # Add Attribute to each node

    print(color_map)
    nx.set_node_attributes(G, color_map, name="colour")

    # Then draw with colours based on attribute values:
    nx.draw(G,
            node_color=nx.get_node_attributes(G, 'colour').values(),
            with_labels=True)

    plt.show()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69456551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档