gpt4 book ai didi

python - 如何使用点列表的 (x,y) 坐标绘制 networkx 图?

转载 作者:行者123 更新时间:2023-12-05 02:47:25 27 4
gpt4 key购买 nike

我的点为 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

最佳答案

这应该可以解决您的问题:

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

结果

Figure with axes on and right positions

背景

对于轴,我使用了上面已经建议的 plt.axis("on")How to make x and y axes appear when using networkx and matplotlib?

此外,我将 spring_layout 替换为您的 points 列表中的位置。

关于python - 如何使用点列表的 (x,y) 坐标绘制 networkx 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64986306/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com