How to animate a line chart in a streamlit page
Asked Answered
T

1

6

I am working with a ML project and I want to display in (relative) real time a chart with a fitness function.

I am using code from this SO answer and it works fine as long as the chart is displayed in the matplotlib window. As soon as I add it to the page, it becomes a static image.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

max_x = 5
max_rand = 10

x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))


def init():  # give a clean slate to start
    line.set_ydata([np.nan] * len(x))
    return line,


def animate(i):  # update the y values (every 1000ms)
    line.set_ydata(np.random.randint(0, max_rand, max_x))
    return line,

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=1000, blit=True, save_count=10)

st.pyplot(plt)

Any idea how to animate a chart? It doesn't have to be matplotlib.

Tipple answered 4/10, 2019 at 13:7 Comment(2)
Change the function animate(i) to update with your new chart data.Mohawk
Yeah, this the first streamlit question ever on stackoverflow :)Resection
T
9

I received my answer on the streamlit forum so I'm just copying the updated code here

import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
import time

fig, ax = plt.subplots()

max_x = 5
max_rand = 10

x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))
the_plot = st.pyplot(plt)

def init():  # give a clean slate to start
    line.set_ydata([np.nan] * len(x))

def animate(i):  # update the y values (every 1000ms)
    line.set_ydata(np.random.randint(0, max_rand, max_x))
    the_plot.pyplot(plt)

init()
for i in range(100):
    animate(i)
    time.sleep(0.1)
Tipple answered 5/10, 2019 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.