Create Interactive Dashboards with Streamlit and Python

Muthu Last Updated : 18 Jul, 2024
5 min read

Introduction

In Data Visualization, Dashboard is the great Graphical User Interfaces that helps you to display the information in a highly interactive and informative way. It helps to visualize the key indicators and trends of the data.

streamlit

The various plots such as bars, pies, line charts, etc. help to explore the dataset and provide us with some useful information. Dashboards are really useful to display the key performance indicators effectively. However, creating dashboards always a tedious task for developers. In this article you will get understanding about the stramlit dashboard how to setup streamlit and import libraries also, for better understanding giving streamlit example.

This article was published as a part of the Data Science Blogathon.

Streamlit - logo

There are some libraries like Plotly, Bokeh in Python that lets you create a dashboard. But I didn’t find these are easy to create a perfect dashboard. Finally, I found some easy ways to create a dashboard which makes you create a quite effective and informative dashboard.

Streamlit

Streamlit is gaining popularity in Machine learning and Data Science. It is a very easy library to create a perfect dashboard by spending a little amount of time. It also comes with the inbuilt webserver and lets you deploy in the docker container.

Setting up Streamlit

Let’s first install Streamlit to our system and run the hello command to verify its working condition. We can quit the running app by using Ctrl+c.

$ pip install streamlit
$ streamlit hello

Below is the command prompt, you can see the app is running perfectly.

streamlit - command prompt

When you run the app, the localhost server will open in your browser automatically. This is the home page of the Streamlit app open-source framework.

streamlit - welcome screen

Import Libraries

Let’s import the necessary libraries using for plotting as well as displaying information.

import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import matplotlib.pyplot as plt

We can display the text in different ways. Streamlit allows you to write the title, header, and also supports various functions.

  1. st.title()- to set the title
  2. st.text() to write the description for the particular graph
  3. st.markdown() to display text as markdown
  4. st.latex() to display the mathematical expressions in the dashboard.
  5. st.write() helps to display everything such as plotly graph, dataframe, functions, model, etc.
  6. st.sidebar() is used for displaying data on the sidebar.
  7. st.dataframe() to display the data frame
  8. st.map() to display the map in just a single line code etc

Setting the title and the sidebar title for Streamlit dashboard

  1. st.title(“Covid-19 Dashboard For India”)
  2. st.markdown(‘The dashboard will visualize the Covid-19 Situation in India’)
  3. st.markdown(‘Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus. Most people infected with the COVID-19 virus will experience mild to moderate respiratory illness and recover without requiring special treatment.’. This app gives you the real-time impact analysis of Confirmed, Deaths, active, and recovered cases of COVID-19 )
  4. st.sidebar.title(“Visualization Selector”)
  5. st.sidebar.markdown(“Select the Charts/Plots accordingly:”)

Load the dataset

Here we are going to use the COVID-19 dataset for dashboard visualization.

DATA_URL=('E:\Data science Projects\NIELIT project\covid_19_world.csv')
@st.cache(persist=True)( If you have a different use case where the data does not change so very often, you can simply use this)

def load_data():
    data=pd.read_csv(DATA_URL)
    return data

covid_data=load_data()

Data Visualization by cases

st.sidebar.checkbox("Show Analysis by State", True, key=1)
select = st.sidebar.selectbox('Select a State',df['state'])

#get the state selected in the selectbox
state_data = df[df['state'] == select]
select_status = st.sidebar.radio("Covid-19 patient's status", ('Confirmed',
'Active', 'Recovered', 'Deceased'))

We have used the Checkbox to choose the analysis by states. Selectbox will display the list of states affected by COVID-19. The radio button to choose the Active, Confirmed, Death, or Recovered cases.

Plotting the graph

def get_total_dataframe(dataset):
    total_dataframe = pd.DataFrame({
    'Status':['Confirmed', 'Recovered', 'Deaths','Active'],
    'Number of cases':(dataset.iloc[0]['confirmed'],
    dataset.iloc[0]['recovered'], 
    dataset.iloc[0]['deaths'],dataset.iloc[0]['active'])})
    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)

After executing this code we can select the cases according to the state you required. The method get_total_dataframe is used to get the dataset to plot the graph for the selected state.

To plot the graph, we have used plotly.express library method. And finally, show the graph using the st.plotly_chart().

The graph showing the cases for Maharashtra.

cases in maharashtra

Showing a dataframe or table

We can also view the dataframe in table view using st.dataframe() and st.table().

def get_table():
    datatable = df[['state', 'confirmed', 'recovered', 'deaths','active']].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
statewise covid cases in india

Conclusion

Streamlit is considered as the fastest growing Machine Learning and Data Science dashboard building platform. It is considered as one of the best dashboard libraries. You can experiment with different datasets to create interactive dashboards.

Hope you like the article and get the understanding about the streamlit dashboard and and you can setup it and import libraries hope you clear about it.

Q1. Is Plotly Dash better than Streamlit?

Streamlit: Easy & Fast for simple apps.
Plotly Dash: Powerful & Customizable for complex apps with great visuals.

Q2.What is Streamlit used for?

Streamlit: Turns Python data scripts into data dashboards and ML app prototypes in minutes.

Responses From Readers

Clear

Mohammed Pervez Manzer
Mohammed Pervez Manzer

Very informative stuf

Christian
Christian

The image you have at the top of this article.. What visualization library is this from?

Anis Boujemaa
Anis Boujemaa

Can you give us the csv file please ? and tell me if **df** exists in the columns or rows of the csv file ? If not can you give us the df where it should be declared and how ? Thank you so much.

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details