【问题标题】:Autoplay a matplotlib FuncAnimation jsthml element自动播放 matplotlib FuncAnimation jsthml 元素
【发布时间】:2020-07-22 12:37:26
【问题描述】:

我正在编写将在 Google Colab 中显示的代码。 Colab 要求您在显示之前使用HTML 函数。这是一个示例代码(来自here):

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML

fig = plt.figure()


def f(x, y):
    return np.sin(x) + np.cos(y)

x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)

im = plt.imshow(f(x, y), animated=True)


def updatefig(*args):
    global x, y
    x += np.pi / 15.
    y += np.pi / 20.
    im.set_array(f(x, y))
    return im,

HTML(animation.FuncAnimation(fig, updatefig, interval=50, blit=True).to_jshtml())

这有效,除非您必须单击“播放”按钮才能播放。如下图:

是否可以生成 jshtml 以便在呈现框时立即播放,就好像它被人点击一样?请注意,代码需要在 Google Colab 中运行,根据我的经验,这比通常的 Jupyter notebook 的限制要多一些。

【问题讨论】:

    标签: python matplotlib jupyter-notebook google-colaboratory


    【解决方案1】:

    显示后可以添加代码点击“播放”

    # this is from your code above
    from IPython.display import HTML, Javascript
    anim = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
    
    # display animation and click play (the 6th button)
    display(HTML(anim.to_jshtml()))
    Javascript('document.querySelector(".anim-buttons > button:nth-child(6)").click()')
    

    这里是a working notebook

    【讨论】:

    • 这最初是有效的,但如果另一个动画已经在播放,它似乎不会用这个 javascript 自动播放新的单元格。 IE。如果您暂停前一个单元格,然后使用此 Javascript 代码重新运行该单元格,则它会再次运行。你知道为什么会这样吗?它应该是一个单独的问题吗?
    • 我不确定。这是我第一次尝试。但是,您不能跨单元调用它。
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2013-11-19
    相关资源
    最近更新 更多