[英]How to draw weight labels with networkx and matplotlib?
我正在研究圖,所以我試圖使用networkx和matplotlib在python中給定字典繪制圖,這是我的代碼:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
graph = {
"A":["B","C"],
"B":["D","E"],
"C":["E","F"],
"D":["B","G"],
"E":["B","C"],
"F":["C","G"],
"G":["D","F"]
}
x=10
for vertex, edges in graph.items():
G.add_node("%s" % vertex)
x+=2
for edge in edges:
G.add_node("%s" % edge)
G.add_edge("%s" % vertex, "%s" % edge, weight = x)
print("'%s' it connects with '%s'" % (vertex,edge))
nx.draw(G,with_labels=True)
plt.show()
我已經嘗試過函數draw_networkx_edge_labels,但是由於我動態添加節點,因此我似乎需要一個我沒有的位置,因此我需要一種方法來繪制適合當前實現的邊緣標簽。
添加完所有節點后即可繪制圖形,以便可以計算位置並根據它們使用nx.draw_networkx_edge_labels(...)
:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
graph = {
"A":["B","C"],
"B":["D","E"],
"C":["E","F"],
"D":["B","G"],
"E":["B","C"],
"F":["C","G"],
"G":["D","F"]
}
x=10
for vertex, edges in graph.items():
G.add_node("%s" % vertex)
x+=2
for edge in edges:
G.add_node("%s" % edge)
G.add_edge("%s" % vertex, "%s" % edge, weight = x)
print("'%s' it connects with '%s'" % (vertex,edge))
# ---- END OF UNCHANGED CODE ----
# Create positions of all nodes and save them
pos = nx.spring_layout(G)
# Draw the graph according to node positions
nx.draw(G, pos, with_labels=True)
# Create edge labels
labels = {e: str(e) for e in G.edges}
# Draw edge labels according to node positions
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.