포인트 목록의 (x, y) 좌표를 사용하여 networkx 그래프를 그리는 방법은 무엇입니까?

Nov 24 2020

점이 x, y이고 축을 볼 수 있도록 점 목록의 (x, y) 좌표를 사용하여 그래프를 플로팅하고 싶습니다. 여기 내 코드와 그래프 사진이 있습니다.

import networkx as nx
import matplotlib.pyplot as plt
def add_edge_to_graph(G,e1,e2,w):
   G.add_edge(e1,e2,weight=w) 

G=nx.Graph()
points=[(1, 10), (8, 10), (10, 8), (7, 4), (3, 1)] #(x,y) points
edges=[(0, 1, 10), (1, 2, 5), (2, 3, 25), (0, 3, 3), (3, 4, 8)]#(v1,v2, weight)

for i in range(len(edges)):
       add_edge_to_graph(G,points[edges[i][0]],points[edges[i][1]],edges[i][2])
       
     
pos = nx.spring_layout(G)
nx.draw(G,pos=pos,node_color='k')
nx.draw(G, pos=pos, node_size=1500)  # draw nodes and edges
nx.draw_networkx_labels(G, pos=pos)  # draw node labels/names
# draw edge weights
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.axis()
plt.show() 

https://i.imgur.com/LbAGBIh.png

답변

1 Sparky05 Nov 24 2020 at 13:00

이렇게하면 문제가 해결됩니다.

import networkx as nx
import matplotlib.pyplot as plt


def add_edge_to_graph(G, e1, e2, w):
    G.add_edge(e1, e2, weight=w)


G = nx.Graph()
points = [(1, 10), (8, 10), (10, 8), (7, 4), (3, 1)]  # (x,y) points
edges = [(0, 1, 10), (1, 2, 5), (2, 3, 25), (0, 3, 3), (3, 4, 8)]  # (v1,v2, weight)

for i in range(len(edges)):
    add_edge_to_graph(G, points[edges[i][0]], points[edges[i][1]], edges[i][2])

# you want your own layout
# pos = nx.spring_layout(G)
pos = {point: point for point in points}

# add axis
fig, ax = plt.subplots()
nx.draw(G, pos=pos, node_color='k', ax=ax)
nx.draw(G, pos=pos, node_size=1500, ax=ax)  # draw nodes and edges
nx.draw_networkx_labels(G, pos=pos)  # draw node labels/names
# draw edge weights
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, ax=ax)
plt.axis("on")
ax.set_xlim(0, 11)
ax.set_ylim(0,11)
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)
plt.show()

결과

백 라운드

축의 경우 networkx 및 matplotlib를 사용할 때 x 및 y 축을 표시하는 방법plt.axis("on") 과 함께 위에서 이미 제안한대로 사용 했습니다 .

추가로, 나는 spring_layout귀하의 points목록에 있는 위치 로 대체했습니다 .

HenryMont Nov 24 2020 at 12:39

나는 다음과 같이 축을 켜려고 할 것입니다.

limits = plt.axis("on")

축으로 그리기를 사용할 수 있습니다.