Can I animate a scatter plot?

Hi all,
I have data representing a bunch of points in 2D. They move in time. They’re each one of three colors, and they could change to one of the other colors over time. Is there a nice way to animate this with streamlit? Right now, I’m using matplotlib’s scatterplot, with a loop that updates the positions and colors of each point. I didn’t quite see how to do it with one of the more efficient streamlit things like Altair or Pandas, but hopefully I’m missing something obvious. I can easily store the data however would be most useful (numpy array, pandas dataframe, lots of lists, whatever).

Thanks!
-Michael

Hi @mglerner,

Welcome to the forum :wave:

Does this example where we animate an Altair Scatterplot fit your needs?

Here’s another link where we’re animating other kinds of streamlit elements.

Hi,

That first one is almost exactly what I need. Is there a way to delete the old data? I want this to end up looking like a specific number of points are moving around.

FWIW, I tried the animated line chart code and couldn’t get it to work. Streamlit did not give any errors … but I also didn’t see an animated line chart.

Thanks!

hey @mglerner,

You could do something like this, let me know if this works for you :slight_smile:

import streamlit as st
import altair as alt
from vega_datasets import data
import time

source = data.cars()
chart = st.empty()


for i in source.index:
    data_to_be_added = source.iloc[0: i + 1, :]

    x = alt.Chart(data_to_be_added).mark_circle(size=i * 10).encode(
        x='Horsepower',
        y='Miles_per_Gallon',
        color='Origin',
        tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']
    ).interactive()

    time.sleep(0.2)

    chart.altair_chart(x)

Look into plotly express, it makes certain kinds of animations trivial, and provides nice controls.