在 networkx 图上显示边权重

use*_*931 2 python networkx

我有一个包含 3 列的数据框:f1、f2 和分数。我想绘制一个图形(使用 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()
Run Code Online (Sandbox Code Playgroud)

vur*_*mux 6

您正确地尝试使用nx.draw_networkx_edge_labels. 但它使用labelsasedge_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()
Run Code Online (Sandbox Code Playgroud)

所以结果看起来像:

在此处输入图片说明


PS 您在nx.from_pandas_edgelist. 你应该有:

source='f1', target='f2'

代替:

source='feature_1', target='feature_2'