display edge weights on networkx graph(在网络X图上显示边权重)
本文介绍了在网络X图上显示边权重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含3列的数据帧:f1、f2和SCORE。我想画一个图(使用NetworkX)来显示节点(在f1和f2中)和边值作为‘得分’。我能够画出带有节点及其名称的图表。但是,我无法显示边缘分数。有谁能帮帮忙吗?
这是我到目前为止所拥有的:
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
feature_1 = ['Boston', 'Boston', 'Chicago', 'ATX', 'NYC']
feature_2 = ['LA', 'SFO', 'LA', 'ATX', 'NJ']
score = ['1.00', '0.83', '0.34', '0.98', '0.89']
df = pd.DataFrame({'f1': feature_1, 'f2': feature_2, 'score': score})
print(df)
G = nx.from_pandas_edgelist(df=df, source='feature_1', target='feature_2', edge_attr='score')
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
#nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()
推荐答案
您尝试使用nx.draw_networkx_edge_labels
是正确的。但是它使用labels
作为edge_labels
,并且您没有在任何地方指定它。您应该创建此词典:
labels = {e: G.edges[e]['score'] for e in G.edges}
和取消注释nx.draw_networkx_edge_labels
函数:
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
feature_1 = ['Boston', 'Boston', 'Chicago', 'ATX', 'NYC']
feature_2 = ['LA', 'SFO', 'LA', 'ATX', 'NJ']
score = ['1.00', '0.83', '0.34', '0.98', '0.89']
df = pd.DataFrame({'f1': feature_1, 'f2': feature_2, 'score': score})
print(df)
G = nx.from_pandas_edgelist(df=df, source='f1', target='f2', edge_attr='score')
pos = nx.spring_layout(G, k=10) # For better example looking
nx.draw(G, pos, with_labels=True)
labels = {e: G.edges[e]['score'] for e in G.edges}
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()
因此结果将如下所示:
附注:
nx.from_pandas_edgelist
中的源/目标也不正确。您应该:
source='f1', target='f2'
而不是:
source='feature_1', target='feature_2'
这篇关于在网络X图上显示边权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在网络X图上显示边权重


基础教程推荐
猜你喜欢
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01