[英]display edge weights on networkx graph
我有一個包含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()
因此結果將如下所示:
PS您在nx.from_pandas_edgelist
也有不正確的源/目標。 你應該有:
source='f1', target='f2'
代替:
source='feature_1', target='feature_2'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.