![](/img/trans.png)
[英]NetworkX DiGraph() to Graph() with edge weights not summed, how to sum weights?
[英]How to get position of edge weights in a networkx graph?
目前, networkx
庫中有一個用於獲取所有節點位置的函數: spring_layout
。 引用文檔,它返回:
dict : 由節點鍵控的位置字典
並且可以用作:
G=nx.path_graph(4)
pos = nx.spring_layout(G)
我想要類似的東西來訪問加權圖的邊權重的位置。 它應該返回放置邊緣權重數字的位置,最好是在邊緣的中心和邊緣的正上方。 (上面,我的意思是圖形的“外部”,因此對於水平放置的方形圖形的最底部邊緣,它就在邊緣下方)。
所以問題是,是否有類似於spring_layout
的內置spring_layout
來實現這一點? 如果沒有,如何自己解決?
您可以使用nx.draw_edge_labels
返回一個以邊作為鍵和(x, y, label)
作為值的字典
import matplotlib.pyplot as plt
import networkx as nx
# Create a graph
G = nx.path_graph(10)
# Add 2 egdes with labels
G.add_edge(0, 8, name='n1')
G.add_edge(2, 7, name='n2')
# Get the layout
pos = nx.spring_layout(G)
# Draw the graph
nx.draw(G, pos=pos)
# Draw the edge labels
edge_labels = nx.draw_networkx_edge_labels(G, pos)
現在你可以看到變量edge_labels
print(edge_labels)
# {(0, 1): Text(0.436919941201627, -0.2110471432994752, '{}'),
# (0, 8): Text(0.56941037628304, 0.08059107891826373, "{'name': 'n1'}"),
# (1, 2): Text(0.12712625526483384, -0.2901338796021985, '{}'),
# (2, 3): Text(-0.28017240645783603, -0.2947104829441387, '{}'),
# (2, 7): Text(0.007024254096114596, -0.029867791669433513, "{'name': 'n2'}"),
# (3, 4): Text(-0.6680363649371021, -0.26708812849092933, '{}'),
# (4, 5): Text(-0.8016944207643129, -0.0029986274715349814, '{}'),
# (5, 6): Text(-0.5673817462107436, 0.23808073918504968, '{}'),
# (6, 7): Text(-0.1465270298295821, 0.23883392944036055, '{}'),
# (7, 8): Text(0.33035539545007536, 0.2070939421162053, '{}'),
# (8, 9): Text(0.7914739158501038, 0.2699223242747882, '{}')}
現在要得到邊(2,7)
,你只需要做
print(edge_labels[(2,7)].get_position())
# Output: (0.007024254096114596, -0.029867791669433513)
您可以在此處閱讀有關文檔的更多信息。
如果你想提取所有邊的x,y
坐標,你可以試試這個:
edge_label_pos = { k: v.get_position()
for k, v in edge_labels.items()}
#{(0, 1): (0.436919941201627, -0.2110471432994752),
# (0, 8): (0.56941037628304, 0.08059107891826373),
# (1, 2): (0.12712625526483384, -0.2901338796021985),
# (2, 3): (-0.28017240645783603, -0.2947104829441387),
# (2, 7): (0.007024254096114596, -0.029867791669433513),
# (3, 4): (-0.6680363649371021, -0.26708812849092933),
# (4, 5): (-0.8016944207643129, -0.0029986274715349814),
# (5, 6): (-0.5673817462107436, 0.23808073918504968),
# (6, 7): (-0.1465270298295821, 0.23883392944036055),
# (7, 8): (0.33035539545007536, 0.2070939421162053),
# (8, 9): (0.7914739158501038, 0.2699223242747882)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.