使用NetworkX/Matplotlib绘制坐标位置正确的节点

2024-06-23 20:07:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道x/y轴是翻转的(柏林在汉堡东南),但我需要手动修复还是matplotlib/networkx可以帮我修复?如果需要手动操作,有没有最好的方法?

import networkx as nx

G = nx.Graph()

G.add_node('Hamburg', pos=(53.5672, 10.0285))
G.add_node('Berlin', pos=(52.51704, 13.38792))

nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, node_size=0)

enter image description here


Tags: 方法posimportnetworkxaddnodegetmatplotlib
2条回答

你可以用

from matplotlib import pyplot

pyplot.gca().invert_yaxis()
pyplot.gca().invert_xaxis()

打印前可以反转位置。

pos = {city:(long, lat) for (city, (lat,long)) in nx.get_node_attributes(G, 'pos').items()}
nx.draw(G, pos, with_labels=True, node_size=0)

该命令的作用是获取字典nx.get_node_attributes('pos'),并查找所有项。一个项看起来像(city, (lat, long)),因此它以该格式读入每个项,然后在新字典pos中创建一个条目,以便pos[city]=(long,lat)

相关问题 更多 >

    热门问题