Appending to scatter chart sub-plots

This is one of those situations where trying to tie together info from the tutorials and advanced concepts is failing.

I’ve managed to create scatter sub-plots but now I want to make them live by continuously appending data. Scatter charts appear to only be available through matplotlib but the advanced concept uses the built in chart object so I’m struggling to figure out how to do it.

Any tips?

Thanks

Hey @dazmundo -

In general, to append data to any chart, you use the add_rows function. (You call add_rows on the value returned from the various st. calls.)

However, matplotlib charts aren’t “live” (they don’t live in the browser and therefore aren’t interactive; instead, matplotlib renders your chart to a static image which is then sent to the browser.) So add_rows does not work with matplotlib.

I’d recommend using Altair to render your scatter chart instead. (Streamlit has good support for Altair; it’s actually what st.line_chart, area_chart, and bar_chart all use under the hood.)

For example:

import time
import altair as alt
import numpy as np
import pandas as pd
import streamlit as st

# Generate some random data
df = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])

# Build a scatter chart using altair. I modified the example at
# https://altair-viz.github.io/gallery/scatter_tooltips.html
scatter_chart = st.altair_chart(
    alt.Chart(df)
        .mark_circle(size=60)
        .encode(x='a', y='b', color='c')
        .interactive()
)

# Append more random data to the chart using add_rows
for ii in range(0, 100):
    df = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
    scatter_chart.add_rows(df)
    # Sleep for a moment just for demonstration purposes, so that the new data
    # animates in.
    time.sleep(0.1)

You can read more about Altair here https://altair-viz.github.io/

1 Like

Hi @tim

Great example. I was actually not aware that you can use .add_rows on a st.altair_chart: I thought it was only on the built in streamlit charts. Can you do that on plotly charts as well?

Maybe this is worth making clearer in the documentation as this really expands the useability of Streamlit :slight_smile:

1 Like

Many thanks @tim for the info and example. That was very detailed and very much appreciated.

2 Likes

Hey Marc - that’s a good point! I’ll bring it up at an engineering meeting, thanks for the feedback!

1 Like