1

Possible Duplicate:
How to make the plot not disappear?

I am writing a command line interface python program for analysing some data. It asks the user a bunch of questions and at a few points in the script a matplotlib pyplot plot neds to be shown, but I want to show it and continue with the script something like below:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.plot(np.arange(10),np.arange(10)**2)

plt.show()
print 'continuing the program'

I have tried using plt.draw() along with subplots but it doesn't seem to work inside a script.

edit: I have used plt.ion() which kind of works except the plot windows are unresponsive, and the zoom in tool etc buttons aren't shown

1
  • ... Commented Sep 11, 2012 at 12:36

1 Answer 1

2

plt.show() will not return until the user closes the widget/window. I many cases this behavior is fine. Why should the script proceed while the user spends time looking at a wonderful graph anyway? :-) If you, however, require your program to proceed, make use of the threading module. Invoke plt.show() in a new thread and join() this thread before letting your main thread terminate.

Edit:

It looks like things are not that simple. I created the following test.py:

import threading
from matplotlib import pyplot as p
import time

p.plot([_ for _ in xrange(5)])

t = threading.Thread(target=p.show)
t.start()

for i in xrange(5):
    print "lala %s" % i
    time.sleep(1)

print "Waiting for plot thread to finish..."
t.join()
print "Finished."

Testing it results in this error:

14:43:42 $ python test.py
lala 0
lala 1
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.6/threading.py", line 484, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib/pymodules/python2.6/matplotlib/backends/backend_tkagg.py", line 73, in show
    manager.show()
  File "/usr/lib/pymodules/python2.6/matplotlib/backends/backend_tkagg.py", line 385, in show
    if not self._shown: self.canvas._tkcanvas.bind("<Destroy>", destroy)
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 988, in bind
    return self._bind(('bind', self._w), sequence, func, add)
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 938, in _bind
    needcleanup)
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1101, in _register
    self.tk.createcommand(name, f)
RuntimeError: main thread is not in main loop

I infer from this that p.show() is required to be called from the main thread. Maybe you have to do it the other way round: get your user input in another thread.

Sign up to request clarification or add additional context in comments.

1 Comment

Because I need to get user input about the beautiful graph:p Threading makes sense cheers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.