Search code examples
pythonnetworkx

Networkx: printing graph with fixed positions


I'm trying to draw a graph with data from a csv with the structure:

city,lat,long

every node was created as:

with open('file.csv', 'r', encoding='utf8') as file:
    spamreader = csv.reader(file, delimiter=',')
    next(spamreader)
    for row in spamreader:
        G.add_node(row[0] ,pos=(row[1], row[2]))

And the edges were created as:

for i in G.nodes:
    for j in G.nodes:
        if i == j:
            pass
        else:
            w = getDistanceFromLatLng(float(G.nodes[i]['pos'][0]) ,float(G.nodes[i]['pos'][1]), float(G.nodes[j]['pos'][0]), float(G.nodes[j]['pos'][1]), miles=False)
            G.add_edge(i, j, weight = w)

I'm trying to draw these cities according to their position, but I haven't been able to.


Solution

  • If you're just trying to use the latitude/longitude as coordinates in space, then the following should work:

    pos = {n:[*map(float,G.nodes[n]['pos'])] for n in G.nodes()}
    nx.draw(G, pos = pos, with_labels = True, node_color = 'orange')