Python 在networkx图形上显示边权重
我有一个包含3列的数据框:f1、f2和score。我想画一个图形(使用NetworkX)来显示节点(在f1和f2中)和边值作为“分数”。我能够用节点及其名称绘制图形。但是,我无法显示边缘分数。有人能帮忙吗 这就是我到目前为止所做的:Python 在networkx图形上显示边权重,python,networkx,Python,Networkx,我有一个包含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']
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\u networkx\u edge\u标签
。但是它使用标签
作为边缘标签
,而您没有在任何地方指定它。您应该创建此目录:
labels={e:G.edges[e]['score']for e in G.edges}
并取消注释nx.draw\u networkx\u edge\u标签
函数:
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()
因此,结果如下所示:
另外,您在来自edgelist的nx中的
nx中也有不正确的源/目标。你应该:
source='f1',target='f2'
而不是:
source='feature\u 1',target='feature\u 2'
谢谢!非常感谢!