gpt4 book ai didi

Python Networkx 权重标签定位

转载 作者:行者123 更新时间:2023-12-01 00:36:16 26 4
gpt4 key购买 nike

下面的代码在图中产生了非常“狡猾”的边权重标签放置。请看图片。我希望有一个更好的位置(靠近每条线的中点),同时仍然利用节点的自动定位 - 即我不想手动定位节点。

enter image description here

请问有什么想法吗?还有一个警告 - The iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead.如果有人知道如何解决的话,这将是很好的解决方案。

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np

G = nx.Graph()
G.add_nodes_from(["A", "B", "C"])
G.add_edge("A", "B", weight=5)
G.add_edge("B", "C", weight=7)
G.add_edge("C", "A", weight=2)

pos = nx.spring_layout(G)
weights = nx.get_edge_attributes(G, "weight")
nx.draw_networkx(G, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=weights)

plt.show()

最佳答案

来自documentation of draw_networkx :

draw_networkx(G, pos=None, arrows=True, with_labels=True, **kwds)
Parameters:
[...]
pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will
be computed. See networkx.layout for functions that compute node
positions.

因此,如果您不显式传递 pos,则会生成 spring_layout,但这与您通过生成的布局不同

pos = nx.spring_layout(G)

,因为调用 nx.spring_layout(G) 两次会得到不同的结果:

for a in [0,1]:
pos = nx.spring_layout(G)
print(pos)

输出:

{'A': array([ 0.65679786, -0.91414348]), 'B': array([0.34320214, 0.5814527 ]), 'C': array([-1.        ,  0.33269078])}
{'A': array([-0.85295569, -0.70179415]), 'B': array([ 0.58849111, -0.29820585]), 'C': array([0.26446458, 1. ])}

因此,将相同的 pos 传递给两个绘图函数可以解决问题:

pos = nx.spring_layout(G)
weights = nx.get_edge_attributes(G, "weight")
nx.draw_networkx(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=weights)

关于Python Networkx 权重标签定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com