如何使用点列表的(x,y)坐标绘制networkx图? [英] how to plot a networkx graph using the (x,y) coordinates of the points list?

查看:270
本文介绍了如何使用点列表的(x,y)坐标绘制networkx图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的点为x,y,我想使用点列表的(x,y)坐标绘制图形,以便可以看到轴.这是我的代码和图表的照片

 将networkx导入为nx导入matplotlib.pyplot作为pltdef 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)点edges = [(0,1,10),(1,2,5),(2,3,25),(0,3,3),(3,4,8)]#(v1,v2,权重)对于范围内的我(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)#绘制节点和边nx.draw_networkx_labels(G,pos = pos)#绘制节点标签/名称#绘制边缘权重标签= nx.get_edge_attributes(G,'重量')nx.draw_networkx_edge_labels(G,pos,edge_labels = labels)plt.axis()plt.show() 

背景

对于轴,我使用了上面已经建议的 plt.axis("on")以及https://i.imgur.com/LbAGBIh.png

解决方案

This should solve your problem:

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

Result

Backround

For the axis, I used plt.axis("on") as already suggested above together with How to make x and y axes appear when using networkx and matplotlib?

Additionaly, I replaced the spring_layout with the positions in your points list.

这篇关于如何使用点列表的(x,y)坐标绘制networkx图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆