Networkx Graph边绘制错误

Networkx Graph edge drawing error

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

如果你评论

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

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

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

pos = nw.spring_layout(G)

或任何其他布局算法。

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

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)

注意这里应该是边,不是节点,所以需要从中心节点开始找。