开发者

Interactive figure with OO Matplotlib

开发者 https://www.devze.com 2023-02-11 22:38 出处:网络
Using Matplotlib via the OO API is easy enough for a non-interactive backend: from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

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()
 canva开发者_StackOverflows = 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消