Reload altair chart when new data is added to df

I was initially trying out st.line_chart & it works well with reloading of chart using the add_rows function, when new data is appended.

chart = st.line_chart(df, height=250)
chart.add_rows(df2)

However, the downside is that this matplotlib plotting does not provide much room to tweak the chart, e.g. fixing axis limits, naming axis titles. So I decided to try altair instead.

Altair has much more options to tweak the chart by customising the figure before loading into st.altair_chart, but the problem comes about when I want the chart to reload whenever new data is appending. I cant just chart.add_rows anymore.

So the question is, how can I reload altair charts when new data is added to the dataframe?

I don’t know enough about st.line_chart, but is there a reason you cannot add rows to the dataframe and call chart on that frame again?

Dinesh

Hi, I am not sure how to “call chart on that frame”, would u be able to show a code snippet?

this is my current code for st.line_chart for reloading the chart based on new updates of rows.

cpu_chart = st.line_chart(df height=250)

for i in range(100):
    cpu_chart.add_rows(df2)

For altair, a code like this wouldnt work as it will create a new frame every iteration.

numpy as np
import altair as alt 
df = pd.DataFrame(
    np.random.randn(100, 3),
    columns=['a', 'b', 'c'])

c = alt.Chart(df).mark_circle().encode(
    x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])

st.altair_chart(c, use_container_width=True)

for i in range(100):
  
  df = pd.DataFrame(
      np.random.randn(100, 3),
      columns=['a', 'b', 'c'])

  c = alt.Chart(df).mark_circle().encode(
      x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])

  st.altair_chart(c, use_container_width=True)

Ok, I found the solution myself after looking through some of streamlit’s demos. The trick is to use st.empty() to define a fixed frame to reload on.

Hope this will be helpful to other users. It will be good if the documentation itself give an example on reloading of other charts besides the ones by matplotlib like st.line_chart.

numpy as np
import altair as alt 

chart_row = st.empty()

for i in range(100):
  
  df = pd.DataFrame(
      np.random.randn(100, 3),
      columns=['a', 'b', 'c'])

  c = alt.Chart(df).mark_circle().encode(
      x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])

  chart_row.altair_chart(c, use_container_width=True)