5

I understand how to display matplotlib plots on-screen using the pyplot interface (I think!). I started plotting in a multi-threaded program, and this started causing errors, so I am trying to switch to the object-oriented interface. I can make a simple plot and save to file using

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

fig = Figure()
can = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot((1,2,3))
can.print_figure('test')

But how do I display this plot on the screen? I have seen other code that uses can.draw() but that has no effect.

Also, please let me know if there is anything suboptimal about my code above - I haven't really got to grips with what all these figure, canvas and axes objects do yet.

1 Answer 1

4

Your problem is that you're using a non-interactive backend (Agg rather than TkAgg, GtkAgg, QtAgg, etc). By definition, it doesn't support display to the screen.

However, working with multithreaded code with any gui library will require that the gui's mainloop be run in its own thread.

In other words, switching to a backend that can display to the screen will require a good bit more complexity in your multithreaded code.

There are several different ways to do this, but any generic method will be very inefficient. (The simple solution is to use pyplot.ion and then draw the canvas every x milliseconds in one thread while doing other things in another thread. This is horribly inefficient.)

Can you give a bit more detail about what you're doing? Why are you using threading instead of multiprocessing? (i.e. are you just doing a lot of IO?) What gui library are you using? (If you don't know, then it's probably Tk, as that's the default matplotlib backend.)

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

1 Comment

Thanks a lot for your help. I hadn't realised the answer would be specific to the backend (I tried to work out what pyplot.show() was doing, but failed to find the relevant code). I found this example for Tk, which is very helpful. Mentioning multithreading was probably a red herring - I just had some code that did some number-crunching and saved some plots with pyplot, I tried moving this into a thread so I could look at its results while it was running, and got lots of weird errors.

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.