Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw plots on screen using matplotlib API

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.

like image 343
James Avatar asked Oct 09 '22 10:10

James


1 Answers

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.)

like image 135
Joe Kington Avatar answered Oct 13 '22 10:10

Joe Kington