有关动画模块的正确工作答案,请参阅the answer of ImportanceOfBeingErnest
您的预期功能存在多个问题。动画的进度如何与反转一起工作?会有视频,但按下按钮开始播放?还是应该有单独的框架步骤?我不确定我是否理解动画如何与这种反转功能相结合;我把 matplotlib 动画想象成电影。
我的另一个问题是技术问题:我不确定这可以通过 matplotlib 动画来完成。 The docs explain FuncAnimation 表面上的表现
for d in frames:
artists = func(d, *fargs)
fig.canvas.draw_idle()
plt.pause(interval)
在哪里frames is essentially an iterable。在动画期间动态调整frames 对我来说似乎并不简单,所以这是一个技术障碍。
实际上,您描述的功能在我的脑海中在基于小部件的方法中效果更好。 Buttons 可以传播“动画”,或者您可以使用check button 来修改下一步是前进还是后退。这是我的意思的简单概念证明:
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np # just for dummy data generation
# generate dummy data
ndat = 20
x = np.linspace(0,1,ndat)
phi = np.linspace(0,2*np.pi,100,endpoint=False)
dat = np.transpose([x[:,None]*np.cos(phi),x[:,None]*np.sin(phi)],(1,2,0))
# create figure and axes
fig = plt.figure()
ax_pl = plt.subplot2grid((5,5),(0,0),colspan=5,rowspan=3) # axes_plot
ax_bl = plt.subplot2grid((5,5),(4,0),colspan=2,rowspan=1) # axes_button_left
ax_br = plt.subplot2grid((5,5),(4,3),colspan=2,rowspan=1) # axes_button_right
# create forward/backward buttons
butt_l = Button(ax_bl, '\N{leftwards arrow}') # or u'' on python 2
butt_r = Button(ax_br, '\N{rightwards arrow}') # or u'' on python 2
# create initial plot
# store index of data and handle to plot as axes property because why not
ax_pl.idat = 0
hplot = ax_pl.scatter(*dat[ax_pl.idat].T)
ax_pl.hpl = hplot
ax_pl.axis('scaled')
ax_pl.axis([dat[...,0].min(),dat[...,0].max(),
dat[...,1].min(),dat[...,1].max()])
ax_pl.set_autoscale_on(False)
ax_pl.set_title('{}/{}'.format(ax_pl.idat,dat.shape[0]-1))
# define and hook callback for buttons
def replot_data(ax_pl,dat):
'''replot data after button push, assumes constant data shape'''
ax_pl.hpl.set_offsets(dat[ax_pl.idat])
ax_pl.set_title('{}/{}'.format(ax_pl.idat,dat.shape[0]-1))
ax_pl.get_figure().canvas.draw()
def left_onclicked(event,ax=ax_pl,dat=dat):
'''try to decrement data index, replot if success'''
if ax.idat > 0:
ax.idat -= 1
replot_data(ax,dat)
def right_onclicked(event,ax=ax_pl,dat=dat):
'''try to increment data index, replot if success'''
if ax.idat < dat.shape[0]-1:
ax.idat += 1
replot_data(ax,dat)
butt_l.on_clicked(left_onclicked)
butt_r.on_clicked(right_onclicked)
plt.show()
请注意,我一般对 matplotlib 小部件或 GUI 并没有真正的经验,因此不要期望上述内容符合该主题的最佳实践。我还添加了一些额外的参数要在这里和那里传递,因为我不喜欢使用全局名称,但这在这种情况下可能有点迷信;老实说,我说不出来。此外,如果您在类或函数中定义这些对象,请确保保留对小部件的引用,否则它们可能会在意外垃圾收集时变得无响应。
生成的图形有一个用于绘制散点图的轴,并且有两个按钮可以增加切片索引。数据形状为(ndat,100,2),其中尾随索引定义二维空间中的 100 个点。特定状态:
(没必要这么丑,我只是不想摆弄设计。)
我什至可以想象一个计时器自动更新绘图的设置,并且可以使用小部件设置更新的方向。我不确定如何正确地做到这一点,但我会尝试走这条路,以获得您似乎追求的那种可视化。
另外请注意,上述方法完全缺少 FuncAnimation 会做的 blitting 和其他优化,但希望这不会干扰您的可视化。