gpt4 book ai didi

python - 用坐标绘制 NetworkX Graph

转载 作者:行者123 更新时间:2023-12-05 00:56:04 27 4
gpt4 key购买 nike

我的 networkx 图由具有名为“coords”(x,y) 的属性的对象组成:

import networkx as nx
import matplotlib.pyplot as plt

class device():
def __init__(self, name):
self.name = name
self.coords = (0,0)
def __repr__(self):
return self.name

device1 = device('1')
device1.coords = (20, 5)
device2 = device('2')
device2.coords = (-4, 10.5)
device3 = device('3')
device3.coords = (17, -5)

G = nx.Graph()
G.add_nodes_from([device1, device2, device3])
nx.draw(G, with_labels = True)
plt.show()

每当我绘制它时,matplotlib 都会以困惑的顺序绘制图形。如何根据坐标绘制这样的图形?

最佳答案

nx.draw采用 pos 参数来定位所有节点。它需要一个字典,其中节点作为键,位置作为值。因此,您可以将以上内容更改为:

devices = [device1, device2, device3]
G = nx.Graph()
G.add_nodes_from(devices)

pos = {dev:dev.coords for dev in devices}
# {1: (20, 5), 2: (-4, 10.5), 3: (17, -5)}
nx.draw(G, pos=pos, with_labels = True, node_color='lightblue')
plt.show()

enter image description here

关于python - 用坐标绘制 NetworkX Graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62999488/

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