matplotlib.pyplot.FuncAnimation.save()意外裁剪动画。如何避免这种情况?

问题描述 投票:0回答:1

我想保存通过plt.FuncAnimation()制作的动画。它的侧面有一个长标题和文本框(显示各种参数)。我尝试过ffpmeg(.mp4),枕头(.gif)和imagemagick(.gif)作家。所有尝试都会导致输出文件似乎放大了主图形,从而切断了文本并降低了质量。如何避免这种情况?

[通过plt.savefig()保存数字时出现了相同的问题,但是通过plt.tight_layout()plt.savefig(bbox_inches='tight')解决了这一问题。这些都不适用于plt.FuncAnimation().save()

这里是一个例子:

"""
Matplotlib Animation Example

author: Jake Vanderplas
email: [email protected]
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

ax.set_title('This is a really long title that is cropped in the .mp4, but not the .ipynb output.')

ax.text(3, 0.5, 'Text outside the graph is also cropped in the .mp4, but not the .ipynb output.')

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# 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
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
python matplotlib animation crop
1个回答
0
投票

我设法通过使用空白子图来解决此问题。有关如何完全隐藏子图的详细信息,请参见here。然后,您可以根据需要在该子图中添加形状/文本。

© www.soinside.com 2019 - 2024. All rights reserved.