如何在 networkx 图中获取边权重的位置?

How to get position of edge weights in a networkx graph?

目前networkx library for getting positions of all nodes: spring_layout中有一个函数。引用文档,它 returns:

dict : A dictionary of positions keyed by node

并可用作:

G=nx.path_graph(4)
pos = nx.spring_layout(G)

我想要类似于访问加权图的边权重位置的东西。它应该 return 放置边缘权重数字的位置,最好是在边缘的中心和边缘的正上方。 (在上面,我的意思是在图形的“外部”,因此对于水平放置的方形图形的最底部边缘,它会刚好在边缘下方)。

所以问题是,是否有类似于 spring_layout 的内置功能来实现此目的?如果没有,如何自己解决?

您可以使用 nx.draw_edge_labels 其中 returns 以边作为键和 (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)

您可以阅读有关文档的更多信息 here

如果你想提取所有边的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)}