带有 OO Matplotlib 的交互式图形 [英] Interactive figure with OO Matplotlib
问题描述
通过 OO API 使用 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')
但是如果我尝试用交互式后端重复类似的事情,我会很惨地失败(我什至无法让交互式图形首先出现).有没有人有通过 OO API 使用 Matplotlib 创建交互式图形的示例?
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
不是交互式的.backend_tkagg
(或其他类似的后端之一)是.
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()
但是,老实说,这不是使用oo接口的方法.如果您需要交互式绘图,请执行以下操作:
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()
您仍在使用 oo 界面,您只是让 pyplot
处理创建图形管理器并为您输入 gui 主循环.
You're still using the oo interface, you're just letting pyplot
handle creating the figure manager and enter the gui mainloop for you.
这篇关于带有 OO Matplotlib 的交互式图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!