首页 > 解决方案 > Python networkx 图标签

问题描述

我有两个数据框,用于在 Python 中使用 networkx 创建图形。数据帧 df1(节点坐标)和 df2(边缘信息),如下所示:

    location     x      y
0   The Wall     145    570
2   White Harbor 140    480

    location    x             y 
56  The Wall    Winterfell    259 
57  Winterfell  White Harbor  247 

这是我为尝试绘制它而实现的代码:

plt.figure()
G=nx.Graph()

for i, x in enumerate(df1['location']):
  G.add_node(x, pos=(df1['x'][i], df1['y'][i]))

for x, x2, w in zip(df2['location'], df2['x'], df2['y']):
  G.add_edge(x, x2, weight=w)

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

pos = nx.get_node_attributes(G, 'pos')
weights = nx.get_edge_attributes(G, 'weight') 
nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)

plt.show()

我之前运行了几次,它似乎可以工作,但是现在重新打开 jupyter notebook 并再次运行它之后,它就无法工作了。我主要有两个主要问题。

我一直在看这个几个小时,我似乎无法修复它,有什么想法吗?


编辑: 如果从 nx.draw 中排除 pos=pos,我可以显示标签,但如果我包含它,它将不起作用

标签: pythongraphnetworkx

解决方案


问题是您没有pos为 node 指定任何属性Winterfell,然后当您尝试在其中访问它时draw_networkx_edge_labels找不到它。

如果您尝试给它一个位置属性,请说:

      location    x    y
0      TheWall  145  570
1   Winterfell  142  520
2  WhiteHarbor  140  480

那么就可以正确访问所有节点的属性,正确绘制网络:

plt.figure()
G=nx.Graph()

df1 = df1.reset_index(drop=True)
df2 = df2.reset_index(drop=True)

for i, x in enumerate(df1['location']):
    G.add_node(x, pos=(df1.loc[i,'x'], df1.loc[i,'y']))

for x, x2, w in zip(df2['location'], df2['x'], df2['y']):
    G.add_edge(x, x2, weight=w)

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

pos = nx.get_node_attributes(G, 'pos')
weights = nx.get_edge_attributes(G, 'weight') 
nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)

plt.show()

在此处输入图像描述


推荐阅读