How to Run Animations in Altair and Streamlit | by Angelica Lo Duca | Towards Data Science

Altair is a very popular Python library for data visualisation. Through Altair, you can build very complex charts with few lines of code, since the library follows the guide lines provided by the Vega-lite grammar.
Unfortunately, Altair does not support native animations, because of the complexity of rendering them through Vega-lite.
In this tutorial, I illustrate a mechanism which combines the power of Streamlit with Altair, in order to render an animated line chart.
Streamlit is a very powerful Python library, which permits to build Web apps in Python with few lines of code.
Firstly, I install the required libraries:
pip install streamlitpip install altair
In order to build a Streamlit app, I can write a Python script, which cannot be in the form of a Jupyter notebook, since currently Streamlit does not support Jupyter.
Thus, I create a script, named AltairAnimation.py, I import all the needed libraries to my script:
import pandas as pdimport altair as altimport streamlit as stimport time
Then, I load the dataset. As example, I exploit the number of tourist arrivals to Italy from 2012 to 2020, released by the Eurostat Database. I exploit the Pandas library to load the dataset:
df = pd.read_csv('../sources/tourist_arrivals.csv')
The dataset contains the monthly number of tourists arrivals. I convert the date to a datetime type:
df['date'] = pd.to_datetime(df['date'])
I build an empty graph in Altair through the Chart() class. In details, I specify that I want to draw a line through the mark_line() function. Then, I set the axes (x and y) as well as the width and height of the graph. As default values for the x axis, I set 1:T, where T indicates a time variable. For the y axis, instead, I set the default value to 0:Q, where Q indicates a quantity, i.e. a number.
lines = alt.Chart(df).mark_line().encode(     x=alt.X('1:T',axis=alt.Axis(title='date')),     y=alt.Y('0:Q',axis=alt.Axis(title='value'))).properties(    width=600,    height=300)
I also define a function which updates the chart with the dataframe passed as argument:
def plot_animation(df):    lines = alt.Chart(df).mark_line().encode(       x=alt.X('date:T', axis=alt.Axis(title='date')),       y=alt.Y('value:Q',axis=alt.Axis(title='value')),     ).properties(       width=600,       height=300     )      return lines
I would like to build an animation as the following one:
When the user clicks on the start button, the animation starts, and initially it plots only the first 6 months of the dataframe. Then, other 6 months are added to the plot and so on up to the size of the dataframe.
This can be achieved as follows. Firstly, I define some auxiliary variables:
N = df.shape[0] # number of elements in the dataframeburst = 6       # number of elements (months) to add to the plotsize = burst     # size of the current dataset
Now I can build the Streamlit interface. I draw a chart and a button:
line_plot = st.altair_chart(lines)start_btn = st.button('Start')
Finally, I can build the animation:
if start_btn:   for i in range(1,N):      step_df = df.iloc[0:size]      lines = plot_animation(step_df)      line_plot = line_plot.altair_chart(lines)      size = i + burst      if size >= N:          size = N - 1      time.sleep(0.1)
If the user clicks the Start button (if start_btn:), then a loop starts, up to the number of elements N-1. A partial dataframe is built, including the first size elements. Then the chart is build on this partial dataframe and the variable size is updated.
Eventually, I’m ready to run the Web App. From command line, I can run the following command:
streamlit run AltairAnimation.py
The Web App will be available at the following URL:
http://localhost:8501
In this tutorial, I have illustrated how to build animations in Altair, by exploiting the very powerful Streamlit library.
The full code of the implemented Web App is available in my Github Repository.
I really would thank A B, who wrote this article, which inspired me for mine.
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github.