使用坐标绘制 NetworkX 图表

3
我的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绘图时,它都会以混乱的顺序绘制图形。如何按照坐标绘制这样的图形呢?

1个回答

8

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接