Matplotlib动画未正确保存

2024-04-26 00:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,它在一系列数据点上沿x轴移动一条垂直线。动画与plt.show配合使用效果很好,但输出电影文件时遇到问题。请注意,我对Python非常陌生,尽管我已经玩了一两年了。脚本是通过将this tutorial中的第一个脚本与this previous stack overflow question的答案中给出的脚本相结合来创建的。这条线最终会在静态数据线图上移动,我在这里以对角线的形式呈现。在

电影文件被输出为具有正确的时间长度(1分钟,10秒),但是这条线,应该从最左边移动到最右边,每秒1点,在输出视频中只移动几个像素。在

如果您能提供任何帮助来解决这个问题,我们将不胜感激。在

编辑:我在Ubuntu14.04上运行Python2.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轴,这限制了在屏幕上显示的内容,但是动画仍然会超出显示的轴。在

^{pr2}$

Tags: thetoimport脚本data电影timeplot
1条回答
网友
1楼 · 发布于 2024-04-26 00:33:33

对于编辑的代码,请在对^{}的调用中包含两个附加参数:

  1. frames=2525作为例子选择)-再次设置最大帧数
  2. repeat=False-不要在最大帧数之后重复动画

组合起来,您可以得到以下命令:

anim = animation.FuncAnimation(fig, update, frames=25,
                               interval=1000, blit=True, repeat=False)

这将产生一个经过25帧的动画(在您的例子中,将垂直线从0移动到24)并在那里停止。在

相关问题 更多 >