문제

I am generating random Geometric graph using networkx. I am exporting all the node and edges information into file. I want to generate the same graph by importing all the node and edges information from file.

Code to export the node values and edge information.

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()

I am trying to export it with below code and trying to change the color of some nodes. But it is generating different graph.

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()

How to generate the same graph with few changes in color of some nodes?

도움이 되었습니까?

해결책

If I understand the problem you're having correctly, the trouble is here:

pos=nx.random_layout(G) 
nx.draw_networkx_nodes(G,pos,nodelist=['1','2'],node_color='b') 
nx.draw(G) 

You create a random layout of the graph in the first line, and use it to draw nodes '1' and '2' in the second line. You then draw the graph again in the third line without specifying the positions, which uses a spring model to position the nodes.

Your graph has no extra nodes, you've just drawn two of them in two different positions. If you want to consistently draw a graph the same way, you need to consistently use the pos you calculated. If you want it to be the same after storing and reloading, then save pos as well.

다른 팁

The easiest way to store node position data for your case might be using Python pickles. NetworkX has a write_gpickle() function that will do this for you. Note that the positions are already available as node attributes when you generate a random geometric graph so you probably want to use those when drawing. Here is an example of how to generate, save, load, and draw the same graph.

In [1]: import networkx as nx

In [2]: G=nx.random_geometric_graph(10,0.5)

In [3]: pos = nx.get_node_attributes(G,'pos')

In [4]: nx.draw(G,pos)

In [5]: nx.write_gpickle(G,'rgg.gpl')

In [6]: H=nx.read_gpickle('rgg.gpl')

In [7]: pos = nx.get_node_attributes(H,'pos')

In [8]: nx.draw(H,pos)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top