【问题标题】:Why is matplotlib.animation.FuncAnimation producing a blank ouput in a Jupyter notebook?为什么 matplotlib.animation.FuncAnimation 在 Jupyter 笔记本中产生空白输出?
【发布时间】:2021-04-12 22:32:51
【问题描述】:

我正在学习 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()

【问题讨论】:

    标签: python matplotlib jupyter-notebook matplotlib-animation


    【解决方案1】:

    我在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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 2021-09-18
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多