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

7
我知道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


4
我认为你的更深层次问题在于,你把纬度当作了“x”,经度当作了“y”。实际上,<x,y>应该是<long,lat>。颠倒x和y轴并不能改变这一点。因此,你需要绘制long, lat而不是lat, long - Joe Kington
对于一般情况,请在 nx.draw 中使用 pos 参数,参见 Plot NetworkX Graph with coordinates - yatu
2个回答

3
您可以使用

标签


from matplotlib import pyplot

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

1
好的,太棒了,因为现在我知道纬度/经度必须要交换。谢谢! - user1602492

3

在绘图前,您可以反转位置。

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')并找到其中所有的项。一个项的格式类似于(城市,(纬度,经度)),因此它会按照该格式读取每个项,并在新字典pos中创建一个条目,以便pos[城市]=(经度,纬度)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接