我试图通过以下代码调整两个节点之间的边长.但显然它没有用.任何人都可以指导我在哪里犯错:请注意我已经看过这个帖子(如何在Networkx中指定边长以计算最短距离?)但是没有解决我的问题
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_nodes_from([1,2])
G.add_edge(1,2, length = 10) # I also replaced length with len but no luck
nx.draw(G,with_labels=True)
plt.show() # display
Run Code Online (Sandbox Code Playgroud)
这个怎么样:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from([1,2])
G.add_edge(1,2, length = 10)
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos)
plt.show()
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
您还可以使用draw_networkx_edge_labels
参数来打印出您想要的内容.
Networkx 没有根据给定的一组边长度推断节点位置的布局函数。然而,netgraph是一个用于实现更好的网络可视化的 python 库,它确实在几何节点布局中实现了所需的功能。在下面的示例中,我使用边列表来表示网络,但 netgraph 也接受 networkx、igraph 和 graph-tool Graph 对象。
#!/usr/bin/env python
import matplotlib.pyplot as plt
from netgraph import Graph # pip install netgraph OR conda install -c conda-forge netgraph
# right triangle
edge_length = {
(0, 1) : 0.3,
(1, 2) : 0.4,
(2, 0) : 0.5,
}
edges = list(edge_length.keys())
fig, ax = plt.subplots()
Graph(edges, edge_labels=edge_length, node_layout='geometric',
node_layout_kwargs=dict(edge_length=edge_length), ax=ax)
ax.set_aspect('equal')
plt.show()
Run Code Online (Sandbox Code Playgroud)
如果您只需要节点位置但不想使用 netgraph 进行绘图,则可以使用以下get_geometric_layout
函数计算节点位置:
from netgraph import get_geometric_layout
pos = get_geometric_layout(edges, edge_length)
Run Code Online (Sandbox Code Playgroud)
感谢@DanielDarabos 提供完全不必要但非常感谢的赏金!