简体   繁体   中英

networkx - unknown node position error

I have just started using networkx and am using it to build rooted trees. Apologies if this is a trivial question, I have not been able to find the solution elsewhere. With the following code, I get the error networkx.exception.NetworkXError: Node 4 has no position. (in draw_networkx_nodes).

import networkx as nx 
import matplotlib.pyplot as plt
G = nx.DiGraph() 
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_node(4)
G.add_node(5)
G.add_node(6)
G.add_edge(1,2) 
G.add_edge(1,3)
G.add_edge(2,5)
G.add_edge(2,6)
G.add_edge(3,4)
plt.title("Test") 
pos=nx.graphviz_layout(G,prog='dot') 
nx.draw(G,pos,with_labels=False,arrows=False) 
plt.savefig('nx_test.png') 

This occurs as soon as I create node 4. for example, i get the same error when i have nodes 1 to 4 and edges 1,2 1,3 and 2,4. The code works fine until I had node 4 (with 3 nodes it works well). This also occurs regardless of the order in which i specify the edges.

If I specify the edges directly, I get the same error:

    >>> G4 = nx.DiGraph([(1, 2), (1, 3), (2, 5), (2, 6), (3, 4)])
    >>> nx.draw(G4,pos,with_labels=False,arrows=False) 


    Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/dist-packages/networkx-1.7-py2.7.egg/networkx/drawing/nx_pylab.py", line 133, in draw
        draw_networkx(G,pos=pos,ax=ax,**kwds)
      File "/usr/local/lib/python2.7/dist-packages/networkx-1.7-py2.7.egg/networkx/drawing/nx_pylab.py", line 266, in draw_networkx
        node_collection=draw_networkx_nodes(G, pos, **kwds)
      File "/usr/local/lib/python2.7/dist-packages/networkx-1.7-py2.7.egg/networkx/drawing/nx_pylab.py", line 373, in draw_networkx_nodes
        raise nx.NetworkXError('Node %s has no position.'%e)
       networkx.exception.NetworkXError: Node 4 has no position.

Thanks

This was due to two things: 1) an incorrect installation of graphviz, reinstalling from scratch cleared the error.

Secondly, the line

       pos=nx.graphviz_layout(G,prog='dot') 

must always be placed (and repeated) just before drawing the graph, accounting for the new nodes/edges.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM