Drawing nodes with coordinates in correct position using NetworkX/Matplotlib

12,794

Solution 1

You can use

from matplotlib import pyplot

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

Solution 2

you can invert the positions before plotting.

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)

What the command does is it takes the dictionary nx.get_node_attributes('pos') and finds all the items. An item looks like (city, (lat, long)), so it reads in each item in that format and then creates an entry in the new dictionary pos so that pos[city]=(long,lat).

Share:
12,794
Admin
Author by

Admin

Updated on June 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I know that x/y-axis are flipped (Berlin is south-east of Hamburg), but do I need to fix this manually or can matplotlib/networkx do this for me? And if that needs to be done manually, is there a best way to do it?

    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