[英]Python networkx graph labels
我有两个数据框,用于在 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(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
,我的图形将显示,但不会显示任何标签,即使 with_labels 设置为 true。nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)
现在向我展示了错误不能将序列乘以非 int 类型的“float”我已经看了几个小时了,我似乎无法解决它,有什么想法吗?
编辑:如果从 nx.draw 中排除 pos=pos,我可以让标签显示出来,但如果我包含它,它将不起作用
问题是您没有为节点Winterfell
指定任何pos
属性,然后当您尝试在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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.