Matplotlib: getting a figure to show without plt.show()

Peter Pearson pkpearson at nowhere.invalid
Wed Oct 22 06:57:23 CEST 2014


I'm using Matplotlib to present a "control" window with clickable
buttons, and to plot things in another window when you click buttons,
in the style of the code below.  I'm ashamed of the stinky way I
use "first" to call plt.show the first time data are plotted but then
to call fig.canvas.draw for subsequent data plots.  Can someone tell
me the right way?

If I call plt.show every time, then after about 40 plots I get
"RuntimeError: maximum recursion depth exceeded while calling a Python
object", which makes sense because I'm getting one layer deeper in
callbacks with every plot (plt.show doesn't return).  But if I call
fig.canvas.draw every time, the window for the data plot never appears
on my screen.

Thanks for any suggestions.

##############################
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def callback(event):
    global n, first
    fig = plt.figure(2)
    fig.clear()
    plt.plot([0,1],[0,n])
    n += 1  # (Pretending something changes from one plot to the next.)
    if first:
        first = False
        plt.show()
    else:
        fig.canvas.draw()

global n, first
n = 0
first = True
fig = plt.figure(1)
quit_button = Button(plt.axes([.1,.3,.4,.2]), "Quit")
quit_button.on_clicked(lambda x: plt.close("all"))
plot_button = Button(plt.axes([.1,.1,.4,.2]), "Plot")
plot_button.on_clicked(callback)
plt.show()
##############################

-- 
To email me, substitute nowhere->runbox, invalid->com.



More information about the Python-list mailing list