python - 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 并再次运行它之后,它就无法工作了。我主要有两个主要问题。
- 如果我尝试只运行 line
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)
现在向我显示错误不能将序列乘以“浮点”类型的非整数
我一直在看这个几个小时,我似乎无法修复它,有什么想法吗?
编辑: 如果从 nx.draw 中排除 pos=pos,我可以显示标签,但如果我包含它,它将不起作用
解决方案
问题是您没有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()
推荐阅读
- javascript - 为什么 useQuery 调用会导致我的组件重新渲染?
- ssl - OpenSSL SSL_connect:SSL_ERROR_SYSCALL 连接到 www.google.com:443
- sed - 尝试在 WIndows 上编译 gmp-6.2.1 时使用 'char 9: unterminated `s' command' 失败
- ios - AWS amplify add auth:如何在执行 amplify cli 后添加重定向登录 URI
- angular - 在 NativeScript 视图中动态渲染 FontAwesome 图标
- angular - 我被这个错误困住了。当我按照所有步骤在heroku上部署角度应用程序时
- javascript - 如何在页面加载后 2 秒内使图像淡出
- bash - 确定 Bash 脚本中的总内存和磁盘
- ffmpeg - make ffmpeg 选择了 Nvidia CUDA 而不是 Intel QSV(带有两个视频适配器的 Windows 10)
- javascript - 如何将多个模态框添加到嵌入式 svg 文件?