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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With