为什么 matplotlib.animation.FuncAnimation 在 Jupyter 笔记本中产生空白输出?

Why is matplotlib.animation.FuncAnimation producing a blank ouput in a Jupyter notebook?

我正在学习 Python 的 matplotlib FuncAnimation 方法,但无法获得 运行 的基本贝叶斯共轭动画。当我 运行 这样做时,我的 Jupyter 笔记本中只得到一个空白输出。我也使用 Google Colab 得到相同的结果。如何将动画播放到 运行 并显示?

注意,我可以获得官方动画教程脚本 运行...这只是下面代码的问题。

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gamma, poisson

np.random.seed(0)

fig, ax = plt.subplots()
line, = ax.plot([], [])

def animate(i):
    if i == 0:
        x = np.linspace(0, 30, 1000)
        alpha = 2
        beta = 1
        y = gamma.pdf(x, a=alpha, scale=beta)
        line.set_data(x, y)
        return line,
    else:
        sample = poisson.rvs(4)
        alpha += sample
        beta += 1
        y = gamma.pdf(x, a=alpha, scale=beta)
        line.set_data(x, y)
        return line,
    
%matplotlib notebook
%matplotlib notebook

anim = FuncAnimation(fig, animate, frames=2, blit=True)
plt.show()

我在jupyterlab做动画的时候指定了下面的库,好像是用html5的video函数来画的

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
from IPython.display import HTML
import numpy as np
from scipy.stats import gamma, poisson

np.random.seed(0)

fig, ax = plt.subplots()
line, = ax.plot([], [])

def animate(i):
    if i == 0:
        x = np.linspace(0, 30, 1000)
        alpha = 2
        beta = 1
        y = gamma.pdf(x, a=alpha, scale=beta)
        line.set_data(x, y)
        return line,
    else:
        x = np.linspace(0, 30, 1000)
        alpha = 2
        beta = 1
        sample = poisson.rvs(4)
        alpha += sample
        beta += 1
        y = gamma.pdf(x, a=alpha, scale=beta)
        line.set_data(x, y)
        return line,

anim = FuncAnimation(fig, animate, frames=2, blit=True)
# plt.show()

plt.close()
HTML(anim.to_html5_video())