ValueError: Invalid RGBA argument: nan
ValueError: Invalid RGBA argument: nan
当我尝试绘制具有 1000 个节点的图形时出现错误。原因似乎是由于
事实上我可以在映射器中看到一些 nan 值:
---------------------------------------------------------------------------
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
然后
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])
代码(来自)。请注意下面的代码是有效的,但是当我扩展节点数>500时,会出现上面的错误:
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 消息并正确地将节点与其颜色相关联。希望您能提供一些帮助。
即使有 1000 个节点,您的代码也适用于我,试试 运行 这个:
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()
当我尝试绘制具有 1000 个节点的图形时出现错误。原因似乎是由于
事实上我可以在映射器中看到一些 nan 值:
---------------------------------------------------------------------------
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
然后
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])
代码(来自
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 消息并正确地将节点与其颜色相关联。希望您能提供一些帮助。
即使有 1000 个节点,您的代码也适用于我,试试 运行 这个:
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()