![](/img/trans.png)
[英]how to plot a networkx graph using the (x,y) coordinates of the points list?
[英]Plot NetworkX Graph with coordinates
我的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()
每當我 plot 它 matplotlib 以混亂的順序繪制圖形時。 plot這樣的圖如何根據坐標?
nx.draw
將pos
參數傳遞給 position 所有節點。 它需要一個字典,其中節點作為鍵,位置作為值。 因此,您可以將上述內容更改為:
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.