Reputation: 347
I want to plot graph inside a while loop, but execution is blocked after plt.show(G) command and resumes when i manually kill the plot window.
Code:
while True:
print G.edges()
Q = #coming from a function
if Q > BestQ:
nx.draw(G)
plt.show(G)
if G.number_of_edges() == 0:
break
This is the output of G.edges() for two iterations:
[(0, 1), (1, 2), (1, 4), (1, 9), (2, 6), (3, 5), (5, 7), (5, 8), (5, 10)]
[(0, 1), (1, 4), (1, 9), (2, 6), (3, 5), (5, 7), (5, 8), (5, 10)]
How to make this continue after plotting???
Upvotes: 0
Views: 1089
Reputation: 85683
You have to use interactive on
and plt.draw
.
Here you have a working example.
As I do not have your algorithm to generate your G graphs, I will draw constinuously the same network. Anyway, as each call to nx.draw(G) creates a different graph, you can see it updating the plot at each call.
import matplotlib.pyplot as plt
import time
import networkx as nx
plt.ion() # call interactive on
data = [(0, 1), (1, 2), (1, 4), (1, 9), (2, 6), (3, 5), (5, 7), (5, 8), (5, 10)]
# I create a networkX graph G
G = nx.Graph()
for item, (a, b) in enumerate(data):
G.add_node(item)
G.add_edge(a,b)
# make initial plot and set axes limits.
# (alternatively you may want to set this dynamically)
plot, = plt.plot([], [])
plt.xlim(-1, 3)
plt.ylim(-1, 3)
# here is the plotting stage.
for _ in range(10): # plot 10 times
plt.cla() # clear the previous plot
nx.draw(G)
plt.draw()
time.sleep(2) # otherwise it runs to fast to see
Upvotes: 1