Networkx图形边绘制错误。

3
我有以下代码,可以在随机图中正常工作。但是,当我尝试使用其他类型的图形时,绘制边缘函数会发生错误,特别是边缘位置。
如果您注释掉:
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
pos=nw.get_node_attributes(G,'pos') 对于随机几何图有效。对于其他图,它将设置 pos 为空字典 {} - Joel
2个回答

4

我认为除了random_geometric_graph这种图形初始化方法,其他任何方法都不会自动设置节点位置(因为该图形的连通性取决于节点位置,因此默认情况下应该设置一个节点位置)。如果您使用watts_strogatz_graph检查示例,则返回的字典实际上是空的(尽管它可能应该引发一个KeyError)。

您需要显式地确定布局,例如使用:

pos = nw.spring_layout(G)

或者其他布局算法。

2
您可以从堆栈跟踪中看到,问题出在这一行:
nw.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)

而错误是 KeyError,因此某些内容无法找到。可能需要在此处绘制 edges,但您提供了 nodelist。根据官方文档,绘制edges的方法应接受edgelist而不是nodelist

所以你需要这样做:

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

请注意,这里应该是边缘而不是节点,因此您需要从中心节点找到它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接