简体   繁体   English

Plot NetworkX 坐标图

[英]Plot NetworkX Graph with coordinates

My networkx graph consists of objects that have property named "coords" (x,y):我的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()

Any time when I plot it matplotlib draws graph in a chaotic order.每当我 plot 它 matplotlib 以混乱的顺序绘制图形时。 How to plot such a graph according to coordinates? plot这样的图如何根据坐标?

nx.draw takes a pos parameter to position all nodes. nx.drawpos参数传递给 position 所有节点。 It expects a dictionary with nodes as keys and positions as values.它需要一个字典,其中节点作为键,位置作为值。 So you could change the above to:因此,您可以将上述内容更改为:

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()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM