Reputation: 7919
I am working with a regular network (grid) that I create as:
import networkx as nx
N=100
def graph_creating(N):
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() ) #Dictionary of all positions
return G, pos
I have two ways of iterating the code. In both I remove nodes from the network and attempt to draw it. Depending on whether I create the network initially or within the loop, I get a different behavior when I plot it.
My problem: I want to plot the grid after stage 1 and after stage 2, so to make comparisons with the unaltered grid/graph. I fail to do it properly because:
for
loop, I correctly get the first plots but later plots are empty as the graph is never restored back to its unaltered statu;for
loop, I always end up having the unaltered grid plotted, as if the removal had no effect on it.Where else should the graph-creating block be placed, in order to be able to plot the graph right after stage 1 and 2?
version 1 the graph is created outside the for
loop:
G, pos = graph_creating(N)
nodelist = G.nodes()
for counter in range(5):
G1 = nodelist[2*counter:2*counter+1]
G.remove_nodes_from(G1)
nx.draw_networkx(G, pos = pos)
figurename = 'file{0}.png'.format(counter)
plt.savefig(figurename)
G2=nodelist[2*counter+1:2*counter+2]
G.remove_nodes_from(G2)
nx.draw_networkx(G,pos=pos)
#it's not clear from your original question if you save this figure or not
Result: only the first iteration produces correct plots. Later plots are empty as the graph is never restored back to its unaltered status.
version 2 the graph is created inside the for
loop:
for counter in range(5):
G, pos = graph_creating(N)
nodelist = G.nodes()
G1 = nodelist[2*counter:2*counter+1]
G.remove_nodes_from(G1)
nx.draw_networkx(G, pos = pos)
figurename = 'file{0}.png'.format(counter)
plt.savefig(figurename)
G2=nodelist[2*counter+1:2*counter+2]
G.remove_nodes_from(G2)
nx.draw_networkx(G,pos=pos)
#it's not clear from your original question if you save this figure or not
Result: the calls to nx.draw_networkx
result in the unaltered graph being plotted for each iteration. I wonder if the problem is in the way I call that function, as it always plots the graph with no failed nodes. Why do I have this plotting problem?.
Upvotes: 2
Views: 936
Reputation: 3021
tmp_G = G.copy()
draw_netwokx
or remove_nodes_from
use tmp_G instead of GUpvotes: 4