Skip to content
Advertisement

networkx.exception.NetworkXError: Node 64 has no position

i am getting the error in the title, there are already some questions similar to this but none of theme seems to be working for me. this is my code in python:

G = nx.Graph()
def addnodeoNx():
    for k in randomGraph:
        for j in randomGraph[k]:
            G.add_node(j)
            G.add_edges_from([(k, j)])
addnodeoNx()
print(G)

subax1 = plt.subplot(121)
nx.draw(G, with_labels=True, font_weight='bold')
subax2 = plt.subplot(122)
nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')

basically, i’m trying to draw a randomGraph in NetworkX, in the code above randomGraphis a dictionary, with the keys being all the edges and the values being the array of edges each edge connects to, but when I try to run the code, it gives me the following errors:

File "c:UsersbesanOneDriveDesktopLAMtestall.py", line 124, in <module>
    nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')
  File "C:UsersbesanAppDataLocalProgramsPythonPython39libsite-packagesnetworkxdrawingnx_pylab.py", line 1267, in draw_shell
    draw(G, shell_layout(G, nlist=nlist), **kwargs)
  File "C:UsersbesanAppDataLocalProgramsPythonPython39libsite-packagesnetworkxdrawingnx_pylab.py", line 121, in draw
    draw_networkx(G, pos=pos, ax=ax, **kwds)
  File "C:UsersbesanAppDataLocalProgramsPythonPython39libsite-packagesnetworkxdrawingnx_pylab.py", line 333, in draw_networkx
    draw_networkx_nodes(G, pos, **node_kwds)
  File "C:UsersbesanAppDataLocalProgramsPythonPython39libsite-packagesnetworkxdrawingnx_pylab.py", line 456, in draw_networkx_nodes
    raise nx.NetworkXError(f"Node {e} has no position.") from e
networkx.exception.NetworkXError: Node 19 has no position.

Advertisement

Answer

nlist tells draw_shell which nodes to put into an inner shell and an outer shell. The source code for draw_shell is here.

Then draw_shell creates positions from the node using pos=shell_layout(G, nlist=nlist). Then it draws with nx.draw(G,pos).

The function nx.draw cannot handle drawing if the position of a node has not been defined.

In your case, you’ve put nodes 5 through 9 into one shell and 0 to 4 in another. But any node above 9 doesn’t have a position.


comment

You should always be careful when you pass an argument to a function that you’ve copied from somewhere. It’s likely that the argument’s value is important, otherwise it would have just used a default.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement