我正在處理一個腳本,該腳本沿x軸移動一系列數據點的垂直線。該動畫與plt.show
正常工作,但我無法輸出電影文件。請注意,我對Python很新,儘管我一直在玩它一兩年。該腳本是通過將this tutorial中的第一個腳本與this previous stack overflow question的答案中提供的腳本相結合而創建的。這條線最終將在靜態數據線圖上移動,我在這裏將其作爲對角線呈現。Matplotlib動畫未正確保存
電影文件被輸出爲具有正確的時間長度(1分10秒),但是應該從最左邊移動到最右邊每秒1點的線僅移動幾個像素輸出視頻。
任何幫助,您可能能夠提供解決這個問題將不勝感激。
編輯:我在Ubuntu 14.04上運行Python 2.7.6。
這裏是我的重複性代碼:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import time
# Simulated background data
x = np.linspace(0,61,62)
y = np.linspace(0,6,62)
# Set up the figure, the axis, and the plot element we want to animate
max_height = 6 # max height of y-axis
n_pts = 61 # max length of x-axis
# Original location for progress line
y1 = [0, max_height]
x1 = [0, 0]
fig = plt.figure() # Initialize figure
#ax = fig.add_subplot(111) # Intialize axes
ax = plt.axes(xlim=(0, n_pts), ylim=(0, max_height)) # Set axes limits
line, = ax.plot([], [], lw=2) # Initialize line
# draw the data to the 'background'
line1, = ax.plot(x, y, color='black')
# initialization function: plot the background of each frame
def init():
line.set_data(x1, y1)
return line,
starttime=time.time()
mytimer=0
mytimer_ref=0
# animation function. This is called sequentially
def animate(i):
t = time.time() - starttime
mytimer = t + mytimer_ref
x1 = [mytimer,mytimer]
line.set_data(x1, y1)
return line,
# call the animator.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=61, interval=1000)
# save the animation as an mp4. This requires ffmpeg or mencoder to be
# installed. The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5. You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
writer = animation.writers['ffmpeg'](fps=1)
anim.save('demo.mp4',writer=writer,dpi=dpi)
plt.show()
編輯下面的腳本創建的電影,並將其保存爲MP4。現在的問題是,雖然有61幀動畫,但我無法讓電影在那裏停下來。它每次都會進入100幀。我知道這個問題現在有點老,但任何幫助非常感謝!
我試圖手動設置x軸,它限制了屏幕上顯示的內容,但動畫仍然繼續超出顯示的軸。
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from time import time
from scipy.interpolate import interp1d
max_height = 6 # max height of y-axis
n_pts = 62 # max length of x-axis
x = np.linspace(0,61,62)
y = np.linspace(0,6,62)
# New figure with white background
fig = plt.figure(facecolor = 'white')
ax = plt.axes(aspect=1) # Set axes limits
# Original location for progress line
y1 = [0, max_height]
x1 = [0, 0]
# initialize line
plt.plot(x, y) #plot background
line, = ax.plot([], [], lw=2)
def update(frame):
x1 = frame
line.set_data(x1, y1)
# Return the modified line
return line,
anim = animation.FuncAnimation(fig, update, interval=1000, blit=True)
anim.save('line.mp4', writer='ffmpeg')
plt.show()
仍然沒有答案,但不知何故,保存動畫時忽略'interval'選項。奇怪的是,對「animation.FuncAnimation」的調用實際上並不創建動畫。如果您包含一個保存每個mytimer值的變量,並打印此變量,則只有在調用'anim.save'後才能看到輸出 - 但之前不會。然而,'anim.save'只是調用你的動畫61次,但不遵守'interval'。 – Schorsch
感謝您的反饋。這給了我一點工作,我會更新,如果涉及到任何事情。 –