【问题标题】:Animation not running in Jupiter notebook动画未在 Jupyter 笔记本中运行
【发布时间】:2021-07-02 04:54:17
【问题描述】:

我有一些在 Spyder 中运行的代码,但是当我尝试在 Jupiter 笔记本中运行它时它不起作用(我尝试将 %matplot lib 放在单元格的顶部,但我只是收到以下错误: AttributeError: 'NoneType' 对象没有属性 'lower') 这是代码:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
def randrange(n, vmin, vmax):
   return (vmax - vmin) * np.random.rand(n) + vmin
n = 100
xx = randrange(n, 23, 32)
yy = randrange(n, 0, 100)
zz = randrange(n, -50, -25)
fig = plt.figure()
ax = Axes3D(fig)


def init():
    ax.scatter(xx, yy, zz, marker='o', s=20, c="goldenrod", alpha=0.6)
    return fig,

def animate(i):
    ax.view_init(elev=10., azim=i)
    return fig,

# Animate
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=360, interval=20, blit=True)

有什么想法吗?

【问题讨论】:

    标签: python matplotlib jupyter-notebook spyder


    【解决方案1】:

    Jupiter 环境不具备渲染动画的能力,所以似乎使用了 HTML 视频功能。我是 jupyterLab,我总是用这个来运行。

    import numpy as np
    from matplotlib import pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import animation
    from IPython.display import HTML # updated
    
    def randrange(n, vmin, vmax):
        return (vmax - vmin) * np.random.rand(n) + vmin
    
    n = 100
    xx = randrange(n, 23, 32)
    yy = randrange(n, 0, 100)
    zz = randrange(n, -50, -25)
    fig = plt.figure()
    ax = Axes3D(fig)
    
    
    def init():
        ax.scatter(xx, yy, zz, marker='o', s=20, c="goldenrod", alpha=0.6)
        return fig,
    
    def animate(i):
        ax.view_init(elev=10., azim=i)
        return fig,
    
    # Animate
    anim = animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=360, interval=20, blit=True)
    
    plt.close() # updated
    HTML(anim.to_html5_video()) # updated
    

    【讨论】:

    • 你是否安装了一些东西来避免这个错误:RuntimeError: Requested MovieWriter (ffmpeg) not available
    • 要创建 GIF 图像,我使用以下内容。 from matplotlib.animation import PillowWriter; anim.save('file_name.gif', writer='pillow')我也在ffmpeg中使用这个设置来播放视频。anim.save('file_name.mp4', writer='ffmpeg', fps=30)
    • 可以找到ffmpeg安装here.
    • 干杯不安装它,所以没有它肯定没有办法让动画运行?我认为这与单元格自动设置为内联这一事实有关,但不确定对于具有移动动画的单元格而言,“内联”的等价物是什么。
    • ffmpeg 用于将动画另存为视频。动画不需要它。最后一个代码是将创建的动画显示为 HTML5 中的视频。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2016-10-26
    • 2020-05-17
    • 1970-01-01
    • 2018-09-23
    • 2020-11-18
    • 2021-07-12
    相关资源
    最近更新 更多