2017-04-20 134 views
2

我有以下代码可用于随机图表可以显示。但是,当我尝试使用其他图形类型时,在边缘绘制函数中出现错误。特别是边缘位置。Networkx图形边缘绘制错误

如果你对此有何评论

G = nw.random_geometric_graph(200, 0.125) 

,并取消注释出现

G = nw.barabasi_albert_graph(200, 2) 

错误消息。我是新来的python和NetworkX特别是任何帮助表示赞赏!

import matplotlib.pyplot as plt 
import networkx as nw 

G = nw.random_geometric_graph(200, 0.125) 

#G = nw.watts_strogatz_graph(200, 3, 0.125, seed=None) 
#G = nw.barabasi_albert_graph(200, 2) 

# position is stored as node attribute data for random_geometric_graph 
pos = nw.get_node_attributes(G, 'pos') 

# find node near center (0.5, 0.5) 
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 

# color by path length from node near center 
p = nw.single_source_shortest_path_length(G, ncenter) 

plt.figure(figsize=(8, 8)) 

nw.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4) 
nw.draw_networkx_nodes(G, pos, nodelist=list(p.keys()), node_size=80, node_color=list(p.values()), cmap=plt.cm.Reds_r) 

plt.xlim(-0.05, 1.05) 
plt.ylim(-0.05, 1.05) 
plt.axis('off') 
plt.savefig('random_geometric_graph.png') 
plt.show() 

给出的错误信息是;

--------------------------------------------------------------------------- 
KeyError         Traceback (most recent call last) 
<ipython-input-11-> in <module>() 
    22 plt.figure(figsize=(8,8)) 
    23 
---> 24 nw.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4) 
    25 nw.draw_networkx_nodes(G, pos, nodelist=list(p.keys()), node_size=80, node_color=list(p.values()), cmap=plt.cm.Reds_r) 
    26 

/Users//anaconda/lib/python3.6/site-packages/networkx/drawing/nx_pylab.py in draw_networkx_edges(G, pos, edgelist, width, edge_color, style, alpha, edge_cmap, edge_vmin, edge_vmax, ax, arrows, label, **kwds) 
    513 
    514  # set edge positions 
--> 515  edge_pos = numpy.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) 
    516 
    517  if not cb.iterable(width): 

/Users//anaconda/lib/python3.6/site-packages/networkx/drawing/nx_pylab.py in <listcomp>(.0) 
    513 
    514  # set edge positions 
--> 515  edge_pos = numpy.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) 
    516 
    517  if not cb.iterable(width): 

KeyError: 0 
+2

如果您有错误,请将它们包含在帖子中并突出显示哪条特定行会导致错误 – EdChum

+0

'pos = nw.get_node_attributes(G,'pos')'适用于随机几何图形。对于其他人,它只是将'pos'设置为'{}'(空字典)。 – Joel

回答

3

我不认为任何其他图形初始化方法除了random_geometric_graph设置节点位置自动(如本图中的连通性依赖于节点位置,是有意义的设置一个默认情况下)。如果你用watts_strogatz_graph检查你的例子,返回的字典实际上是空的(尽管它可能会抛出KeyError)。

您需要明确确定布局,例如,使用

pos = nw.spring_layout(G) 

或任何其他布局算法。

1

你可以看到这个问题(从堆栈跟踪)是在这一行:

nw.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4) 

和错误是KeyError,这样的东西不能被发现。可能你需要在这里画edges,但你确实提供了nodelist。根据official docs,绘制edges的方法应该接受edgelist,而不是nodelist

所以,你需要这样做:

nw.draw_networkx_edges(G, pos, edgelist=[SOME_EDGES_HERE], alpha=0.4) 

请注意,这应该是边缘,而不是节点,所以你需要从中心节点找到他们。