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图上显示边权重
基础教程推荐
猜你喜欢
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
