[IPython-User] using matplotlib draw_if_interactive in library code

Fernando Perez fperez.net@gmail....
Sat Oct 6 17:51:36 CDT 2012


Hi Skipper,

On Sat, Oct 6, 2012 at 7:32 AM, Skipper Seabold <jsseabold@gmail.com> wrote:
> Hi,
>
> It's a matplotlib question, but the conclusion on how to work with mpl is
> due to IPython (and programs that interact with mpl similarly) AFAICT.
>
> So I'm curious if someone can go into a bit more detail about the
> conclusions of this thread [1]. Namely,
>
> "don't call show or draw_if_interactive in your library code"
>
> Or rather, what are the exact pitfalls here. I don't understand the possible
> side effects. Is it still true that draw_if_interactive doesn't play well
> with the notebooks?

No, that shouldn't be a problem.  The issue is that show() will try to
pop up a window, which could potentially trigger GUI activity.  show()
is a function whose entire purpose is to cause a side-effect: the
creation of the figure itself.

The standard practice is therefore to put a single show() call at the
end of a script so that figure windows only open at the end.  I do
sometimes put the show() calls earlier, but I do it knowingly because
I *want* figures to pop up half-way through executions.

> We have plotting functions that are designed to update a given axes. I often
> work in interactive mode, and I'd like it if these functions updated my axes
> in the way that I expect (and an R user doing plotting in Python would
> expect). But now I'm forced to litter my user scripts with
> draw_if_interactive rather than handle this for the users in the plotting
> functions. Do I have any other options?

Is a single

plt.show()

as the last line of your scripts not viable? That's sort of the
standard advice we always have given for years.  By delaying the draw
calls, you also gain potentially a lot in performance: matplotlib can
render the whole figure just once, rather than doing it over and over
at potentially quadratic costs.

Fundamentally the message is: show()/draw() are designed to produce  a
side effect, the display of a rendered figure.  Since this side effect
is only meaningful to a human looking at the screen, the decision to
invoke them should be in the hands of said human, not taken by
intermediate libraries that have no way of knowing the context in
which they are being called.

Does that make sense?

Cheers,

f


More information about the IPython-User mailing list