Search code examples
pythonpython-2.7graphnetworkxgraph-drawing

Draw graph with fixed-positioned edges


I am trying to use NetworkX for Python and it was good so far, but I am stuck with drawing.

My data is actually a list of crossroads in the city. Nodes are the crossroads with X,Y (Latitude, Longitude) and edges should be the roads. So far so simple.

So I managed to draw my little city with fixed positions:

    G = nx.Graph()
    for node in nodes:
      attributes = dict(node.items())
      G.add_node(attributes.pop('id'))
      G.node[node.get('id')]['pos'] = attributes.values()

    pos = nx.get_node_attributes(G, 'pos')
    nx.draw(G,pos)
    plt.show()

It looks like this: A map without edges

Exactly like I want it to, but I need to add the edges. So if I add them like:

    G = nx.Graph()
    for node in nodes:
      attributes = dict(node.items())
      G.add_node(attributes.pop('id'))
      G.node[node.get('id')]['pos'] = attributes.values()

    for link in links:
      attributes = dict(link.items())
      G.add_edge(attributes.pop('from'), attributes.pop('to'))

    pos = nx.get_node_attributes(G, 'pos')
    nx.draw(G,pos)
    plt.show()

I get this horrible error:

Traceback (most recent call last):
   File "ms/Main.py", line 28, in <module>
 nx.draw(G,pos)
   File "/usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py", line 131, in draw
 draw_networkx(G, pos=pos, ax=ax, **kwds)
    File "/usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py", line 265, in draw_networkx
 edge_collection = draw_networkx_edges(G, pos, **kwds)
    File "/usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py", line 610, in draw_networkx_edges
 minx = numpy.amin(numpy.ravel(edge_pos[:, :, 0]))
    File "/usr/local/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 2216, in amin
 out=out, keepdims=keepdims)
    File "/usr/local/lib/python2.7/site-packages/numpy/core/_methods.py", line 29, in _amin
 return umr_minimum(a, axis, None, out, keepdims)
 TypeError: cannot perform reduce with flexible type

If I do not set the fixed positions I am able to draw it no problem, but I quite need the edges to be static. Any advice? Thanks a lot!


Solution

  • The X,Y data is not being treated as numbers.

    You can fix it with this:

     xy = attributes.values()
     G.add_node(attributes.pop('id'), dict([('pos', (float(xy[0]),float(xy[1])) )]))
    

    Note: this answer was edited into the question by the OP. I've moved it down here into the answers section and made it a community wiki so I won't earn any rep for it.