Add Animated Charts To Your Dashboards With Streamlit-Python | by That Data Bloke | Towards Data Science

I have been thinking of trying out Streamlit for a while. So last weekend, I spent some time tinkering with it. If you have never heard of this tool before, it provides a very friendly way to create custom interactive Data web-apps for your Data Science and Machine Learning projects using Python. You can interact with the user to get inputs and display dynamic charts, tables, maps etc. Their official gallery might be a good place to start. It will give you a glimpse of what you can achieve with Streamlit. You would also find a long list of tweets from the Streamlit community going creative with the tool in their own unique ways. Do check them out for some inspiration. Streamlit can be downloaded using the pip install command (pip install streamlit).
In this article, I have shared a sample animated bar chart built using Streamlit. Although, some of the information to achieve this is available in bits and pieces, I couldn’t find much information on animated charts in one place. I hope this will help somebody who is looking to add an animated chart in their Streamlit Dashboard.
Let’s talk about the data a little bit. Tennis being my favorite sport, I decided to do build something around it (and also because I really really really miss Wimbledon 💔). Anyway, after scouting the internet for a while, I stumbled across something that I thought I could use. Roger Federer, Rafael Nadal, Novak Djokovic & Andy Murray were fondly referred as the ‘Big Four’ until 2017. Between them, they have dominated the sport from 2004 to 2017.
The data set has weekly ATP ranking data which has the information like the player name, ranking points, player ranking, and date of ranking. In streamlit, you can also view your dataframe as a table. After some basic formatting my final dataframe looks like below.
I wanted to build an animated bar chart that shows how the Big Four ranked against each other for this period of almost two decades. For the animation, I kept replacing the weekly data in the in chart after a certain time delay inside a for loop . This gave it an animated look and feel.
For visualization purposes, initially I started with the good old Matplotlib library but I ran into some issues and decided to go forward with Altair, which is another visualization library you can use with python. In my experience, I found it to have a better look and feel than Matplotlib to use in my data app. Streamlit supports both of these libraries and a few others as well.
For the UI, I decided to give users the ability to select the range of year themselves and run the animation for the time period of their choice. After selecting the time range, once they press the button ‘Cue Chart’ the animations would begin. I have used the ‘Range Slider’ & ‘Button’ features to perform this.
Range Slider: The purpose of the range slider is to select a range of numbers. It can be created with this single line of code. The function returns a tuple with values selected by the user.
x = st.slider('Select the year range',1996, 2017, (1996, 2017))# 'Select the year range' -> Text to display# 1996 -> The lower bound# 2017 -> The higher bound# (1996, 2017) -> Default selected range
Button: I added a button because I didn’t want the animation to start on its own after the user selects the time range. The button can be created as shown below. I run the animation code inside this ‘if’ statement. The st.button() function returns a boolean true when user performs a click event.
if(st.button('Cue Chart')):    #run the animation. Value is 'True' when user clicks on it.
I used the Altair python library for creating the bar chart. I created a function (plot_bar_animated_altair) that takes two inputs - the weekly data for the Big Four players and week name. It then plots a bar chart. My final formatted dataframe looks like below which will be used to plot the charts. The streamlit function st.dataframe(df) displays a dataframe object in the following fashion.
import streamlit as stimport pandas as pdimport timeimport altair as altfrom altair import Chart, X, Y, Axis, SortField, OpacityValue#---------------------------------------------------------------## Creating an empty chart in the beginning when the page loads#---------------------------------------------------------------#bars = alt.Chart(data).mark_bar().encode(    x=X('1:Q',axis=Axis(title='ATP Ranking Points'),    y=Y('0:Q',axis=Axis(title='The Big Four'))    ).properties(        width=650,         height=400    )# This global variable 'bar_plot' will be used later onbar_plot = st.altair_chart(bars)def plot_bar_animated_altair(df,week):    bars = alt.Chart(df, title="Ranking as of week :"+week).encode(        x=X('ranking_points:Q',axis=Axis(title='ATP Ranking                Points'),         y=Y('full_name:N',axis=Axis(title='The Big Four'), sort='-x'),    color=alt.Color('full_name:N'),     .properties(                 width=650,                  height=400     )if st.button('Cue Chart'):    for week in week_list:        # weekly_df -> this dataframe (sample shown above) contains        # data for a particular week which is passed to        # the 'plot_bar_animated_altair' function.        # week -> Current week title, eg:-  2016-06-10                bars = plot_bar_animated_altair(weekly_df,week)        time.sleep(0.01)                 bar_plot.altair_chart(bars)        st.balloons()  # Displays some celebratory balloons for glamour!
In the demonstration below, I have selected the entire range from 1996 to 2017 and in the beginning you will notice only one bar here (for Roger Federer) because the other three had not turned professional yet. As the weeks pass, you can see the overall ATP Ranking points change and the other players enter in the subsequent years. Their current ranking is displayed as a label against the bars. The bars are sorted so that the higher ranked player always appears on the top.
In conclusion, by the end of this side project I was quite impressed with the simplicity of Streamlit. To achieve this using any other tool would have definitely taken me a lot more time. I hope this article helps save you some time if you are looking to create an animated chart.
Given the growing support that it is receiving lately, I am sure they will add a ton of other useful features. Thank you for reading and wish you a great week ahead!