Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interactive figure with OO Matplotlib

Using Matplotlib via the OO API is easy enough for a non-interactive backend:

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

 fig = Figure()
 canvas = FigureCanvas(fig)
 ax = fig.add_subplot(1,1,1)
 ax.plot([1,2,3])
 canvas.print_figure('test.png')

But if I try and repeat something similar with interactive backends, I fail miserably (I can't even get the interactive figure to appear in the first place). Does anyone have any examples of using Matplotlib via the OO API to create interactive figures?

like image 858
astrofrog Avatar asked Feb 17 '11 15:02

astrofrog


People also ask

Can you make matplotlib interactive?

But did you know that it is also possible to create interactive plots with matplotlib directly, provided you are using an interactive backend? This article will look at two such backends and how they render interactivity within the notebooks, using only matplotlib.

Is matplotlib asynchronous?

Asynchronous Plotting in Matplotlib: rather than call savefig directly, add plots to an asynchronous queue to avoid holding up the main program. Makes use of multiple processes to speed up the writing out.

Is matplotlib better than Plotly?

Matplotlib is also a great place for new Python users to start their data visualization education, because each plot element is declared explicitly in a logical manner. Plotly, on the other hand, is a more sophisticated data visualization tool that is better suited for creating elaborate plots more efficiently.

What does Fig Canvas Flush_events () do?

canvas. flush_events(): It holds the GUI event till the UI events have been processed. This will run till the loop ends and values will be updated continuously.


1 Answers

Well, you need to be using a backend that supports interaction!

backend_agg is not interactive. backend_tkagg (or one of the other similar backends) is.

Once you're using an interactive backend, you need to do something more like this:

import matplotlib.backends.backend_tkagg as backend
from matplotlib.figure import Figure

manager = backend.new_figure_manager(0)
fig = manager.canvas.figure
ax = fig.add_subplot(1,1,1)
ax.plot([1,2,3])
fig.show()
backend.show()

Honestly, though, this is not the way to use the oo interface. If you're going to need interactive plots, do something more like this:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot([1,2,3])
plt.show()

You're still using the oo interface, you're just letting pyplot handle creating the figure manager and enter the gui mainloop for you.

like image 51
Joe Kington Avatar answered Oct 19 '22 16:10

Joe Kington