我有以下代碼可用於隨機圖表可以顯示。但是,當我嘗試使用其他圖形類型時,在邊緣繪製函數中出現錯誤。特別是邊緣位置。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
如果您有錯誤,請將它們包含在帖子中並突出顯示哪條特定行會導致錯誤 – EdChum
'pos = nw.get_node_attributes(G,'pos')'適用於隨機幾何圖形。對於其他人,它只是將'pos'設置爲'{}'(空字典)。 – Joel