Networkx: Regenerate the Random Geometric Graph with previously stored Node values and edges in file

StackOverflow https://stackoverflow.com/questions/8382403

  •  28-10-2019
  •  | 
  •  

Frage

I am generating Random Geometric Graph and storing node and edges information using write_adjlist into file.

Code: python1.py

G=nx.random_geometric_graph(10,0.5) 
filename = "ipRandomGrid.txt" 
fh=open(filename,'wb') 
nx.write_adjlist(G, fh) 
nx.draw(G) 
plt.show()

Now from the second file I am trying to generate the graph with the same node and edges information. I am using read_adjlist to find the information.

Code: python2.py

filename = "ipRandomGrid.txt" 
fh=open(filename, 'rb') 
G=nx.Graph() 
G=nx.read_adjlist("ipRandomGrid.txt") 
pos=nx.random_layout(G) 
nx.draw_networkx_nodes(G,pos,nodelist=[1,2],node_color='b') 
nx.draw(G) 
plt.show()

It's showing me below error.

raise nx.NetworkXError('Node %s has no position.'%e) 
networkx.exception.NetworkXError: Node 1 has no position. 

I think the problem is with the pos variable. Can some one help me to solve this issue?

War es hilfreich?

Lösung

Consider the following interactive session:

>>> import networkx as nx
>>> G = nx.random_geometric_graph(10, 0.5)
>>> with open("junk.txt", "wb") as f:
...   nx.write_adjlist(G, f)
...
>>> G.nodes()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> with open("junk.txt", "rb") as f:
...   G2 = nx.read_adjlist(f)
...
>>> G2.nodes()
[u'1', u'0', u'3', u'2', u'5', u'4', u'7', u'6', u'9', u'8']
>>>

When reading the node list from the file, the nodes identities are treated as strings, not as numbers. Thus, you're getting an error because you're trying to plot two non-existent nodes 1 and 2. Change them to strings ('1' and '2') and it should work fine.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top