【发布时间】:2016-02-15 19:43:26
【问题描述】:
我正在尝试在 NetworkX 中可视化图形。我需要像这样为图形着色:中心节点需要着色为深色。然后,所有更远的节点都需要颜色变浅,但是当我运行代码时,我得到了这个错误:
错误:无法将参数类型
nx.draw_networkx_nodes(G,pos,nodelist=p.keys(),node_size=90,
node_color=p.values(),cmap=plt.cm.Reds_r)
我认为问题出在:
node_color=p.values()
代码是:
import numpy
import pandas
import networkx as nx
import unicodecsv as csv
import community
import matplotlib.pyplot as plt
# Generate the Graph
G=nx.davis_southern_women_graph()
# Create a Spring Layout
pos=nx.spring_layout(G)
# Find the center Node
dmin=1
ncenter=0
for n in pos:
x,y=pos[n]
d=(x-0.5)**2+(y-0.5)**2
if d<dmin:
ncenter=n
dmin=d
""" returns a dictionary of nodes and their distance to the node
supplied as an argument. We will then use these distances
to determine colors"""
p=nx.single_source_shortest_path_length(G,ncenter)
plt.figure(figsize=(8,8))
nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4)
nx.draw_networkx_nodes(G,pos,nodelist=p.keys(),node_size=90,
node_color=p.values(),cmap=plt.cm.Reds_r)
plt.show()
完整的追溯
Traceback (most recent call last):
File "<ipython-input-4-da1414ba5e14>", line 1, in <module>
runfile('C:/Users/Desktop/Marvel/finding_key_players.py', wdir='C:/Users/Desktop/Marvel')
File "C:\Users\Anaconda33\lib\site- packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "C:\Users\Anaconda33\lib\site packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Desktop/Marvel/finding_key_players.py", line 70, in
<module>
cmap=plt.cm.Reds_r)
File "C:\Users\Anaconda33\lib\site-packages\networkx\drawing\nx_pylab.py", line 399, in draw_networkx_nodes
label=label)
File "C:\Users\Anaconda33\lib\site-packages\matplotlib\axes\_axes.py", line 3606, in scatter
colors = mcolors.colorConverter.to_rgba_array(c, alpha)
File "C:\Users\Anaconda33\lib\site-packages\matplotlib\colors.py", line 391, in to_rgba_array
if alpha > 1 or alpha < 0:
ValueError: Cannot convert argument type <class 'numpy.ndarray'> to rgba array
【问题讨论】:
-
也许您的 matplotlib 或 networkx 版本已损坏(或只是较旧)?我有 matplotlib-1.3.1 和 networkx-1.11,它适用于这些。
-
两个模块都升级了,还是一样。
-
OK - 为了帮助您,我们需要包含错误详细信息的完整回溯。我相信你的代码是正确的。这可能是其中一个库不匹配或有问题,可能是 matplotlib 或 numpy。
-
我把整个回溯放在代码下。我认为错误在 matplotlib/colors.py 中,所以我用另一个文件运行了原始的 colors.py 文件,但显然以前的文件也可以,因为错误保持不变。感谢您的帮助
-
感谢您的回溯。我可以看到错误,但我不明白为什么会触发它。也许其他人熟悉这个问题。对我来说,它看起来不像是 networkx 错误。