在网络X图上显示边权重 [英] display edge weights on networkx graph

查看:89
本文介绍了在网络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图上显示边权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆