Build Your First Data Visualization Web App in Python Using Streamlit | by Mala Deep | Towards Data Science

As a data science disciple, I used to work more in jupyter notebook, conducting EDA, designing and developing the model, and presenting the result on the notebook only. Sometimes, I tried to connect the Flask model and give it a working view for the audience, but connecting and developing a model with the front end seems time-consuming and tedious. Then I started exploring alternative and came to Streamlit, which is one of the great ways to share machine learning/data science models, analyses, and visualization without worrying much about the front end at all.
“Streamlit is the next step in ML and data science tools.” — Dominik Mortiz from Vega-Lite
Streamlit is an open-source Python library growing fast, making it easy to produce beautiful custom web-apps for data science and its subdomain. It is also an excellent tool that allows us to create highly interactive dashboards. The best thing about Streamlit is, it doesn’t require any knowledge of web development. If you know Python, you’re good to go!
I love streamlit because it brings some advanced models and visuals to a non-technical team. It lets you go from jupyter notebook to a sleek web app worthy of offering to an audience with minimum effort.
Here, we will learn to build self-exploratory visualization by working with Streamlit visual expression’s power, and I assume you have a good understanding of working with jupyter notebook.
Here’s the full code for this tutorial if you would like to follow along as you progress through the tutorial and here’s the final product.
Python 3.7 version or Plus
Streamlit 0.60 version or Plus
Pandas library
NumPy library
Seaborn library
Matplotlib library
Sublime Text editor for the Python script
Let’s first install Streamlit to our system through the terminal for Mac or command prompt for windows. Here I am using terminal.
$ pip install streamlit
Once finished, let’s run the Streamlit.
$ streamlit hello
Once you run the above command, the localhost server will open in your browser, automatically showing the home page of the Streamlit with few demo contents.
For this demo, I am using Palmer Penguins data. The data were collected and made available by Dr. Kristen Gorman and Palmer Station, Antarctica, LTER. Here we are saving the data as “Penguin data.csv”
github.com
To create self-exploratory visualization on Palmer Penguins where user can 1. Explore daw data2. See statistical description3. Create own graphs (count plot, box plot, and displot as per user’s choice)
Once we download the data, let’s open a new file in any text editor( here I am using a sublime text editor) and name it app.py
Importing core packages and please note we are using ‘st’ as Streamlit command.
import streamlit as st from PIL import Image 
Importing data visualization and data manipulation packages
import matplotlib.pyplot as plt import matplotlibmatplotlib.use("Agg")import seaborn as snsimport pandas as pd import numpy as np
Connecting to data.
DATA_URL = ("Penguin data.csv")
Till now, our code looks like this
Now, let’s give some heading and some info using markdown( you must be feeling WOW, yes markdown is accepted ^_^). And also, let’s add one image.
Remember you can use st.markdown( ) instead of streamlit.markdown( ) as we imported Streamlit as ‘st’.
st.markdown("# Self Exploratory Visualization on palmerpenguins")st.markdown(“Explore the dataset to know more about palmerpenguins”)img=Image.open('images/palmerpenguins.png')st.image(img,width=100)st.markdown(“**Penguins** are some of the most recognizable and beloved birds in the world and even have their own holiday: **World Penguin Day is celebrated every year on April 25**. Penguins are also amazing birds because of their physical adaptations to survive in unusual climates and to live mostly at sea. Penguins propel themselves through water by flapping their flippers.  Bills tend to be long and thin in species that are primarily fish eaters, and shorter and stouter in those that mainly eat krill.”)st.markdown(“The data presented are of 3 different species of penguins - **Adelie, Chinstrap, and Gentoo,** collected from 3 islands in the **Palmer Archipelago, Antarctica.**”)
To run the app on the terminal or command prompt:
$ streamlit run app.py
Once you run the app, here is the result.
Now, to make the process more interactive, let’s add a button using st.button, and once the user clicks on it, we will show an image with some balloon effect using st.balloons( )
if st.button("Meet the Palmer Penguins"):    img=Image.open('images/lter_penguins.png')    st.image(img,width=700, caption="We are  Penguin 🐧")st.markdown(    "The data was collected and made available by **[Dr. Kristen Gorman](https://www.uaf.edu/cfos/people/faculty/detail/kristen-gorman.php)** and **[Palmer Station, Antarctica, LTER](https://pal.lternet.edu/)**.")    images=Image.open('images/meet.png')    st.image(images,width=600)    #Ballons    st.balloons()
Here, you do not need to re-run the app as Streamlit gets automatically updated. You will see a button with text: Meet the Palmer Penguins
Once you click the button, we will see these cute images of penguins with flying balloons.
Now, let’s highlight what’s in data using st.info( ) and again add some pictures.
st.info(“ The dataset contains the different aspect between the species like Body Mass (g), Flipper Length (mm), Culmen Length (mm), Culmen Depth (mm) etc.”)img=Image.open(‘images/beak.jpg’)st.image(img,width=700)
and it renders
Now, here comes the moment to allow the user to explore the data. We will create a side panel using st.sidebar and add some markdown on it with st.sidebar.markdown( ) where we will add some buttons to explore the data as per their need. We also need to load data with nrows option, parse it and show a user the info when the data is completed.
st.sidebar.markdown("## Side Panel")st.sidebar.markdown(“Use this panel to explore the dataset and create own viz.”)df = pd.read_csv(DATA_URL, nrows = nrows)    lowercase = lambda x:str(x).lower()    df.rename(lowercase, axis='columns',inplace=True)    return dfst.header(“Now, Explore Yourself the Palmer Penguins”)# Create a text element and let the reader know the data is loading.data_load_state = st.text('Loading palmerpenguins dataset...')    # Load 10,000 rows of data into the dataframe.df = load_data(100000)    # Notify the reader that the data was successfully loaded.data_load_state.text('Loading palmerpenguins dataset...Completed!')images=Image.open('images/meet.png')st.image(images,width=600)
Working on our sidebar, we add options and info for user’s self-exploration.We are adding here:
title with st.title( )
subheading with st.subheading( )
checkbox with st.checkbox( )
writing the output on the screen with st.write()
# Showing the original raw dataif st.checkbox("Show Raw Data", False):    st.subheader('Raw data')    st.write(df)st.title('Quick  Explore')st.sidebar.subheader(' Quick  Explore')st.markdown("Tick the box on the side panel to explore the dataset.")if st.sidebar.checkbox('Basic info'):    if st.sidebar.checkbox('Dataset Quick Look'):        st.subheader('Dataset Quick Look:')        st.write(df.head())    if st.sidebar.checkbox("Show Columns"):        st.subheader('Show Columns List')        all_columns = df.columns.to_list()        st.write(all_columns)       if st.sidebar.checkbox('Statistical Description'):        st.subheader('Statistical Data Descripition')        st.write(df.describe())    if st.sidebar.checkbox('Missing Values?'):        st.subheader('Missing values')        st.write(df.isnull().sum())
and it renders
As you see, we used Streamlit syntax and have Python data manipulation and visualization code in it.
For example: To have a look at the data set in jupyter notebook, we do:
df.head()
and in Streamlit, we are also allowing the user to check the box to view the raw data using if statement:
if st.sidebar.checkbox('Dataset Quick Look'):        st.subheader('Dataset Quick Look:')        st.write(df.head())
Now, we will dive into creating graphics. The concept is the same as the above example, i.e., we will use the seaborn library in Streamlit to show the graphic, controlled by if statement. We are creating count plot, histogram or distplot and box plot.
st.title('Create Own Visualization')st.markdown("Tick the box on the side panel to create your own Visualization.")st.sidebar.subheader('Create Own Visualization')if st.sidebar.checkbox('Graphics'):    if st.sidebar.checkbox('Count Plot'):        st.subheader('Count Plot')        st.info("If error, please adjust column name on side panel.")        column_count_plot = st.sidebar.selectbox("Choose a column to plot count. Try Selecting Sex ",df.columns)        hue_opt = st.sidebar.selectbox("Optional categorical variables (countplot hue). Try Selecting Species ",df.columns.insert(0,None))                fig = sns.countplot(x=column_count_plot,data=df,hue=hue_opt)        st.pyplot()                            if st.sidebar.checkbox('Histogram | Distplot'):        st.subheader('Histogram | Distplot')        st.info("If error, please adjust column name on side panel.")        # if st.checkbox('Dist plot'):        column_dist_plot = st.sidebar.selectbox("Optional categorical variables (countplot hue). Try Selecting Body Mass",df.columns)        fig = sns.distplot(df[column_dist_plot])        st.pyplot()                                     if st.sidebar.checkbox('Boxplot'):        st.subheader('Boxplot')        st.info("If error, please adjust column name on side panel.")        column_box_plot_X = st.sidebar.selectbox("X (Choose a column). Try Selecting island:",df.columns.insert(0,None))        column_box_plot_Y = st.sidebar.selectbox("Y (Choose a column - only numerical). Try Selecting Body Mass",df.columns)        hue_box_opt = st.sidebar.selectbox("Optional categorical variables (boxplot hue)",df.columns.insert(0,None))        # if st.checkbox('Plot Boxplot'):        fig = sns.boxplot(x=column_box_plot_X, y=column_box_plot_Y,data=df,palette="Set3")        st.pyplot()
and it renders
Now, for a little touch-up, adding data source info, artwork acknowledgment.
st.sidebar.markdown("[Data Source](https://data.world/makeovermonday/2020w28)")st.sidebar.info(" [Source Article](https://github.com/allisonhorst/palmerpenguins) | [Twitter  Tags](https://twitter.com/allison_horst/status/1270046399418138625)")st.sidebar.info("Artwork by [Allison Horst](https://twitter.com/allison_horst) ")st.sidebar.info("Self Exploratory Visualization on palmerpenguins - Brought To you By [Mala Deep](https://github.com/maladeep)  ")st.sidebar.text("Built with  ❤️ Streamlit")
and it renders
This ends our process. Here’s the full code for this tutorial, and here’s the final product you just developed along with me.
Within just 20 minutes, you have developed a self-exploratory visualization app. Here, we’ve covered interactive widgets, data frames, titles, images, Markdown, plot rendering. Now, you experiment with different datasets to create interactive data visualization app, and I will be happier to see your progress on Streamlit.
Featured in Weekly Roundup on Streamlit’s community forum
Click here to learn more on creating this kind of app in free of cost from DataCamp.(Affiliated Link)
If you have any queries regarding the article or want to work together on your next Streamlit project, ping me on LinkedIn.
Streamlit Surpasses Flask
Streamlit tutorial
Knowing These 5 HCI’s Principles Will Make Your Data Visualization Look Amazing
Little Known Ways to Make your Data Visualization Awesome
Streamlit + Heroku = Magic?