0

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

3
  • try calling plt.ion() before the while loop. Commented Oct 12, 2014 at 8:15
  • try plt.draw(), plt.show() may not be the best option Commented Oct 12, 2014 at 8:25
  • plt.ion() not working. Commented Oct 12, 2014 at 9:02

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

plt.draw() is not showing any figure. Any idea why??
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.
I am on linux and using Spyder IDE. It didn't give any error. It just didn't draw anything.
try it on command line, out from Spyder. I have no linux box here but I will try it in ubuntu this afternoon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.