Matplotlib animation in Streamlit through HTML/JS

So this is my little discovery of the day, you can convert a Matplotlib animation to a static HTML/JS, and should work well for small animations.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import streamlit as st
import streamlit.components.v1 as components

def update_line(num, data, line):
    line.set_data(data[..., :num])
    return line,

fig = plt.figure()

# Fixing random state for reproducibility

data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
line_ani = animation.FuncAnimation(fig, update_line, 25, fargs=(data, l), interval=50, blit=True)

st.title("Embed Matplotlib animation in Streamlit")
components.html(line_ani.to_jshtml(), height=1000)

Need to look further into it (I guess for longer animations it could break down because of size), but really matplotlib keeps surprising me everyday…

1 Like