对于文章【matplotlib基础】--动画的一些补充

发布时间 2023-09-21 14:13:16作者: 浑水摸鱼真菌

在阅读了 https://www.cnblogs.com/wang_yb/p/17719014.html 这篇文章后,自己也动手试了试,但是在 jupyter notebook 中无法显示完整的动画流程,所得到的只是一张空白的图片

image

当然,即使加上 %matplotlib inline 魔法函数也是空白的。在询问了chatgpt后,得到了解决方法。在原来的代码的基础上,引用 IPythonHTMLdisplay 函数。

import numpy as np

# import matplotlib # remove
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML, display  # add

x = np.linspace(-8, 8, 100)
y = np.sin(x)

fig, ax = plt.subplots()
(g,) = ax.plot(x, y)


def update(frame):
    y = np.sin(x[:frame])
    g.set_data(x[:frame], y)


anim = animation.FuncAnimation(fig, update, interval=50, frames=len(x)) # modify
display(HTML(anim.to_jshtml())) # add

重新运行后,得到了我们想要的结果。你可以将鼠标放在按钮上以显示作用。

image

对于动画导出,则可以调用 matplotlib 中的方法,通过修改导出的后缀名,导出视频或者gif。

from matplotlib.animation import FFMpegWriter

...其他内容不变

writer = FFMpegWriter(fps=30, metadata=dict(artist='Me'), bitrate=1800)
anim = animation.FuncAnimation(fig, move_point, interval=50, frames=len(x))
anim.save('animation.mp4', writer=writer)