Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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???

share|improve this question
    
try calling plt.ion() before the while loop. – Dominik Neise Oct 12 '14 at 8:15
    
try plt.draw(), plt.show() may not be the best option – ThePredator Oct 12 '14 at 8:25
    
plt.ion() not working. – suri Oct 12 '14 at 9:02

1 Answer 1

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
share|improve this answer
    
plt.draw() is not showing any figure. Any idea why?? – suri Oct 12 '14 at 11:55
    
Do you refer to my code ?. The code posted is working perfect with python 2.7 in windows 7. It shows the figure and refresh it 10 times. Did you copied it exactly as it is and got nothing draw? Did you get any error ? If you refer to your own code you should post the minimal executable example that doesnt work in your case. – joaquin Oct 12 '14 at 23:09
    
I am on linux and using Spyder IDE. It didn't give any error. It just didn't draw anything. – suri Oct 13 '14 at 5:46
    
try it on command line, out from Spyder. I have no linux box here but I will try it in ubuntu this afternoon – joaquin Oct 13 '14 at 8:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.