Plot NetworkX Graph with coordinates

僤鯓⒐⒋嵵緔 提交于 2020-07-23 04:06:33

问题


My networkx graph consists of objects that have property named "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. How to plot such a graph according to coordinates?


回答1:


nx.draw takes a pos parameter to position all nodes. 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()



来源:https://stackoverflow.com/questions/62999488/plot-networkx-graph-with-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!