Using Streamlit to create interactive WebApps from simple Python scripts

Nishtha Goswami
The Startup
Published in
6 min readJun 9, 2020

What if someone tells you can create an interactive web app under 150–200 lines of code? Interesting right. Streamlit provides you with the same opportunity to create beautiful web apps using simple python scripts and a few streamlit calls.

Streamlit is an open-source framework to create data science and machine learning apps for data exploration in the fastest way possible. What I like most about streamlit is it gives you a real-time coding experience. You can start your streamlit app and every time you save, you see your code reflecting in the browser at the same time. Neat right!

In this post, we will be building a Streamlit web app for Covid-19 Impact Analysis in India. I have created the complete website and you can go through it here — www.corona-updates.in. We will not be going deep into pandas and plotly but this tutorial will be more focused on Streamlit. We will be looking at some Pandas library functions but we will explore Streamlit in depth. So, without wasting any time let’s get started.

Requirements:

  1. Streamlit
  2. Pandas
  3. plotly.express

Install streamlit using pip:

pip install streamlit

Once the installation is complete you can test it by running the sample app.

streamlit hello

You can run your streamlit web app named app.py using:

streamlit run app.py

As you are all set with Streamlit, let’s create our web app now. Create a python file app.py and import the libraries you will be needing to create and python script along with streamlit.

1. Importing the database

We are importing the database for Covid-19 India’s impact using this amazing API: https://api.covid19india.org.

Here, in the load_data() method, we are reading the .csv file using pandas library and we are making our code efficient by caching the data. But as this data for Covid-19 keeps changing, we are clearing our cache every 5 mins or for a maximum of 20 entries. If you have a different use case where the data does not change so very often, you can simply use @st.cache(persist=True)

2. Creating title, text content and side menu

Streamlit supports markdown so it’s pretty easy to use different font sizes in our web app. It also supports HTML by passing a parameter: unsafe_allow_html=True to the st.markdown() call and thus, we can style our text the way we want.

The description shows in blue color because we used HTML to give the custom color as blue. We can also use header and subheader like we used st.title() for different headings. Or we can use markdown for that purpose.

//will also give the same result as st.title()
st.markdown("# 🦠 Covid-19 Impact in India")

If you notice in the picture, anything we call with sidebar will show in the sidebar.

st.sidebar.title('Select the parameters to analyze Covid-19 situation')

3. Inserting checkbox, radio buttons and slider

st.sidebar.checkbox("Show Analysis by State", True, key=1)
select = st.sidebar.selectbox('Select a State',data['State'])
#get the state selected in the selectbox
state_data = data[data['State'] == select]
select_status = st.sidebar.radio("Covid-19 patient's status", ('Confirmed',
'Active', 'Recovered', 'Deceased'))
  • Checkbox — The first parameter in the checkbox defines the title of the checkbox, the second parameter defines True or False i.e. whether it is checked by default or not and the third parameter defines the unique key for the checkbox.
  • Selectbox — This selectbox contains all the Indian States. The first parameter is the title of the selectbox and the second parameter defines a list of values to be populated in the selectbox. Here, the second parameter is a column name ‘State’ in the .csv file we loaded before. You can open and explore the table yourself. In the next line, we are getting the data entries in state_data for only the selected state from the selectbox. We can pass a key parameter here as well.
  • Radio buttons — This is just for your reference and we are not actually using it in our web app for now. The first parameter is, as usual, the title of the radio group and the second parameter accepts a tuple of options. We can pass a key parameter here as well.

4. Plotting a graph

def get_total_dataframe(dataset):
total_dataframe = pd.DataFrame({
'Status':['Confirmed', 'Active', 'Recovered', 'Deaths'],
'Number of cases':(dataset.iloc[0]['Confirmed'],
dataset.iloc[0]['Active'], dataset.iloc[0]['Recovered'],
dataset.iloc[0]['Deaths'])})
return total_dataframe
state_total = get_total_dataframe(state_data)if st.sidebar.checkbox("Show Analysis by State", True, key=2):
st.markdown("## **State level analysis**")
st.markdown("### Overall Confirmed, Active, Recovered and " +
"Deceased cases in %s yet" % (select))
if not st.checkbox('Hide Graph', False, key=1):
state_total_graph = px.bar(
state_total,
x='Status',
y='Number of cases',
labels={'Number of cases':'Number of cases in %s' % (select)},
color='Status')
st.plotly_chart(state_total_graph)

The method get_total_dataframe() is used to get the data frame to plot the graph for the selected state. dataset.iloc[0][Confirmed] will return the first entry of the column ‘Confirmed’ and as we are passing only the selected state’s data, we will have only one entry in each Confirmed, Recovered, Active and Deceased columns. (Check out the .csv file)

The checkbox Show Analysis by State is unchecked we will not see the State level Analysis section on our main screen. Similarly, if the Hide Graph checkbox is checked, we will not see the graph.

To plot the graph we will use plotly.express library’s bar method. The first parameter is the dataframe we want to plot, the second parameter is the column for the x-axis, the third parameter is the column for the y-axis, labels parameter is optional in case you want to change the name of a column for the graph and the color parameter here is to color code the graph on the basis of the Status column from the data frame.

And finally, to show the graph in our web app we use the st.plotly_chart() method. We can alternatively use, st.write() as well to show the graph.

5. Showing a dataframe or table

  • st.dataframe(): The first picture is a result of st.dataframe() for the same dataset used in the second picture. You can also use st.write() which internally calls st.datframe().
  • st.table(): We obtained the table in the second picture using st.table(). This shows all the data in the dataframe without any scroll.
def get_table():
datatable = data[['State', 'Confirmed', 'Active', 'Recovered', 'Deaths']].sort_values(by=['Confirmed'], ascending=False)
datatable = datatable[datatable['State'] != 'State Unassigned']
return datatable
datatable = get_table()
st.markdown("### Covid-19 cases in India")
st.markdown("The following table gives you a real-time analysis of the confirmed, active, recovered and deceased cases of Covid-19 pertaining to each state in India.")
st.dataframe(datatable) # will display the dataframe
st.table(datatable)# will display the table

In get_table() we get the sorted dataframe by highest ‘confirmed’ cases of a state obtained from the select box. We also remove the row with State as ‘State Unassigned’ from the dataset.

That’s it! Yes, it is that simple. :)

You are all set to create your own web apps and experiment with Streamlit. This post was on how to create a Streamlit app using simple Python scripts and I hope you enjoyed it. I have created another detailed tutorial on how to deploy this web app using AWS EC2. Please go check it out and let me know your views.

I have created a complete Streamlit web app for Covid-19 Impact in India and deployed it using AWS EC2. You can view it here — www.corona-updates.in. Please provide your valuable feedback in the comments section. Thank you :)

--

--