2016-02-15 20 views
0

我试图在NetworkX中显示图形。我需要像这样着色图表:中心节点需要着色为黑色。然后,所有更远的节点都需要着色得更浅,但是当我运行代码时,出现此错误:使用NetworkX在Python中可视化图形

错误:无法将参数类型<类'numpy.ndarray'>转换为行上的rgba数组:

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() 

Full Traceback

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 
+0

也许你要么matplotlib或networkx的断裂(或只是较早)的版本?我有matplotlib-1.3.1和networkx-1.11,它适用于那些。 – Aric

+0

我升级了两个模块,但错误仍然相同。 –

+0

好的 - 为了帮助你,我们需要完整的回溯和错误细节。我相信你的代码是正确的。它可能与其中一个库不匹配或存在问题,可能是matplotlib或numpy。 – Aric

回答

0

该错误出现在绘制节点的函数中。 p.keys()值必须放在nodelistnode_color的列表中,否则它不起作用。

所以正确的路线是:

nx.draw_networkx_nodes(G,pos,nodelist=list(p.keys()),node_size=80,node_color=list(p.values()), cmap=plt.cm.Reds_r) 
plt.axis('off') 
plt.show()