Autoplay a matplotlib FuncAnimation jsthml element

Viewed 379

I'm writing code that will be displayed in Google Colab. Colab requires you to use HTML function before displaying. This is an example code (from 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())

This works except you have to click the "play" button for it to play. As shown below:

example image

Is it possible to generate jshtml such that it will play immediately when box is rendered, as if it's clicked by a human? Note that the code needs to work in Google Colab, which in my experience is slightly more limiting than usual Jupyter notebook.

1 Answers

You can add the code to click "Play" after display

# 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()')

Here's a working notebook.

Related