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

Drawing nodes with coordinates in correct position using NetworkX/Matplotlib

我知道 x/y-axis 被翻转了(柏林在汉堡的东南部),但我需要手动解决这个问题还是 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)

您可以使用

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