爲了與動畫模塊正常工作答案見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)
,其中尾部指數在2d空間中定義100個點。特定狀態:
(它不必是這個醜陋的,我只是不想與設計撥弄)
我甚至可以想像的設置,其中一個計時器自動更新繪圖,並可以使用小部件設置更新的方向。我不知道如何做到這一點,但我會試圖追求這種可視化的道路,你看起來像後。
另請注意,上述方法完全缺少blitting和FuncAnimation
會執行的其他優化,但希望這不會干擾您的可視化。
謝謝你解釋。它以某種方式不會發生在我身上,這可以通過使用發生器來解決。 – LemurPwned