Techno Blender
Digitally Yours.

Getting Started With Streamlit Web Based Applications | by Andy McDonald | May, 2022

0 81


A gentle introduction to creating Streamlit web apps

Photo by Caspar Camille Rubin on Unsplash

Streamlit is an open source python based framework for developing and deploying interactive data science dashboards and machine learning models. This means that you do not have to rely on a team of front end developers or spend large amounts of time learning web design languages such as HTML, CSS or Javascript in order to deploy your dashboard or model.

Streamlit was founded in 2018 by ex Google engineers who had gained first hand experience of the challenges faced when developing and deploying machine learning models and dashboards.

It is built ontop of Python and supports many of the mainstream Python libraries such as matplotlib, plotly and pandas.

If you want to dive into the full capabilities of Streamlit be sure to check out their excellent documentation at the link below.

The data for this tutorial can be found at the GitHub repository link below. It orginates from a Kaggle dataset that contains information about global Earthquakes.

The original data is available at the link below and is usable under CC0: Public Domain.

https://www.kaggle.com/datasets/usgs/earthquake-database?select=database.csv

I have released an accompanying video tutorial for this article, which can be accessed below:

Before we can run Streamlit apps, we first need to install the library. This can simply be done using the following command if you are using PIP.

pip install streamlit

Create an app.py file

In your chosen Python IDE, create a new file called app.py.

Importing the Libraries

The first coding step in the process is to import the required libraries. For this simple app we will be importing streamlit, pandas and matplotlib.

#Import the required Librariesimport streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

Running The Streamlit App

To confirm streamlit has been installed and imported correctly and that it can be run, go to the terminal and navigate to where your app.py file is located and run the following command:

streamlit run app.py 

Your browser window should open and you will be presented with a blank streamlit window like the one below. You will also be presented with the web address in the terminal should you wish to open up the app in another browser.

Once your web browser opens, you will notice two things, a hamburger menu in the top right and the text Made with Streamlit in the bottom left.

Initial Streamlit app after using streamlit run app.py. Image created by the author.

Adding Text to the Streamlit App

Now that we have confirmed Streamlit is running we can begin adding elements to our app.

To allow people to understand what our app is about we can give it a title and a short description by using st.title and st.text.

# Add a title and intro textst.title('Earthquake Data Explorer')
st.text('This is a web app to allow exploration of Earthquake Data')

When you save the app.py file, you will see new items appear on your streamlit app in the top right. This informs you that the source file has changed and you have two options.

Options that appear in streamlit after saving changes to the source code files. Image by the author.

Rerun — Clicking this will rerun the app and refresh the display. This will need to be pressed each time you make and save changes to your source files.

Always Rerun — Clicking this will automatically rerun the app any time changes are saved to the source file.

After selecting one of the options, the app will now display our entered title and text.

Streamlit app showing content from using st.title and st.write. Image by the author.

Creating a File Uploader Within Streamlit

One of the great things about Streamlit is that users can upload their own files. This is achieved through st.file_uploader().

# Create file uploader objectupload_file = st.file_uploader('Upload a file containing earthquake data')

This little snippet of code does a lot of the heavy lifting when it comes to creating a way for users to upload files. When you add this and rerun the app, you get a nicely presented upload box, where you can manually browse for a file or drag and drop a file.

The file uploader dialogue using st.file_uploader(). Image by the author.

Once we have the file uploader setup, we now need to add some basic logic to detect when a file has been uploaded. If it has, then read the uploaded csv file.

if upload_file is not None:   # Read the file to a dataframe using pandas
df = pd.read_csv(upload_file)

All remaining code can now be placed indented and under this if statement. This way the subsequent code will not be run unless the file has been uploaded.

Display Pandas Describe and Data Within Streamlit

Accessing the df.describe() and df.head() methods from pandas is very simple. We wrap these functions inside of the st.write() method and all of the formatting will be sorted automatically.

# Create a section for the dataframe statistics
st.header('Statistics of Dataframe')
st.write(df.describe())
# Create a section for the dataframe header
st.header('Header of Dataframe')
st.write(df.head())

To test if this is working, select the CSV file (kaggle_significant_earthquakes_database.csv) from the Streamlit Tutorial Series GitHub repository and use the file uploader to upload it to the app.

Once the file has been uploaded the statistics of the data along with the first five rows should now be displayed.

Example of displaying pandas functions using the st.write method in streamlit. Image by the author.

Display a Matplotlib Figure With Streamlit

The final step for this simple app is to display a figure from matplotlib.

First, we need to define a figure and the axes. In this example I have assigned them to plt.subplots().

Under this, we can then create the plot, which will be a scatter plot of earthquake depth versus earthquake magnitude.

We then wrap the fig in st.pyplot().

fig, ax = plt.subplots(1,1)ax.scatter(x=df['Depth'], y=df['Magnitude'])
ax.set_xlabel('Depth')
ax.set_ylabel('Magnitude')
st.pyplot(fig)

When we go back to our app after it has been rerun we will now see the matplotlib figure.

Displaying a matplotlib figure using streamlit’s st.pyplot() function.

The figure that is returned is a standard matplotlib figure and does not feature any interactive functionality. Instead of using matplotlib, it is possible to use plotly to create interactive plots.

Full Code

Here is the full code to generate a very simple web app using the Streamlit library.

#Import the required Librariesimport streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
# Add a title and intro text
st.title('Earthquake Data Explorer')
st.text('This is a web app to allow exploration of Earthquake Data')
# Create file uploader object
upload_file = st.file_uploader('Upload a file containing earthquake data')
# Check to see if a file has been uploaded
if upload_file is not None:
# If it has then do the following: # Read the file to a dataframe using pandas
df = pd.read_csv(upload_file)
# Create a section for the dataframe statistics
st.header('Statistics of Dataframe')
st.write(df.describe())
# Create a section for the dataframe header
st.header('Header of Dataframe')
st.write(df.head())
# Create a section for matplotlib figure
st.header('Plot of Data')
fig, ax = plt.subplots(1,1)
ax.scatter(x=df['Depth'], y=df['Magnitude'])
ax.set_xlabel('Depth')
ax.set_ylabel('Magnitude')
st.pyplot(fig)

Here is the final web app generated with the code above. The app is very static and will only change when new files are uploaded.

Streamlit web based app to visualise earthquake data. Image by the author.

Within this short tutorial we have seen how to create a very simple web application with Streamlit. It allows us to load in data to our app and immediately display descriptive statistics and a matplotlib figure. The current app is static, meaning that the user will only see a static figure and the data with no interaction or updating of the code through parameters. This can easily be enhanced using selection boxes, plotly and many other Streamlit features.

If you want a handy little cheatsheet to use alongside Streamlit, then check out this one from the streamlit documentation.


A gentle introduction to creating Streamlit web apps

Photo by Caspar Camille Rubin on Unsplash

Streamlit is an open source python based framework for developing and deploying interactive data science dashboards and machine learning models. This means that you do not have to rely on a team of front end developers or spend large amounts of time learning web design languages such as HTML, CSS or Javascript in order to deploy your dashboard or model.

Streamlit was founded in 2018 by ex Google engineers who had gained first hand experience of the challenges faced when developing and deploying machine learning models and dashboards.

It is built ontop of Python and supports many of the mainstream Python libraries such as matplotlib, plotly and pandas.

If you want to dive into the full capabilities of Streamlit be sure to check out their excellent documentation at the link below.

The data for this tutorial can be found at the GitHub repository link below. It orginates from a Kaggle dataset that contains information about global Earthquakes.

The original data is available at the link below and is usable under CC0: Public Domain.

https://www.kaggle.com/datasets/usgs/earthquake-database?select=database.csv

I have released an accompanying video tutorial for this article, which can be accessed below:

Before we can run Streamlit apps, we first need to install the library. This can simply be done using the following command if you are using PIP.

pip install streamlit

Create an app.py file

In your chosen Python IDE, create a new file called app.py.

Importing the Libraries

The first coding step in the process is to import the required libraries. For this simple app we will be importing streamlit, pandas and matplotlib.

#Import the required Librariesimport streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

Running The Streamlit App

To confirm streamlit has been installed and imported correctly and that it can be run, go to the terminal and navigate to where your app.py file is located and run the following command:

streamlit run app.py 

Your browser window should open and you will be presented with a blank streamlit window like the one below. You will also be presented with the web address in the terminal should you wish to open up the app in another browser.

Once your web browser opens, you will notice two things, a hamburger menu in the top right and the text Made with Streamlit in the bottom left.

Initial Streamlit app after using streamlit run app.py. Image created by the author.

Adding Text to the Streamlit App

Now that we have confirmed Streamlit is running we can begin adding elements to our app.

To allow people to understand what our app is about we can give it a title and a short description by using st.title and st.text.

# Add a title and intro textst.title('Earthquake Data Explorer')
st.text('This is a web app to allow exploration of Earthquake Data')

When you save the app.py file, you will see new items appear on your streamlit app in the top right. This informs you that the source file has changed and you have two options.

Options that appear in streamlit after saving changes to the source code files. Image by the author.

Rerun — Clicking this will rerun the app and refresh the display. This will need to be pressed each time you make and save changes to your source files.

Always Rerun — Clicking this will automatically rerun the app any time changes are saved to the source file.

After selecting one of the options, the app will now display our entered title and text.

Streamlit app showing content from using st.title and st.write. Image by the author.

Creating a File Uploader Within Streamlit

One of the great things about Streamlit is that users can upload their own files. This is achieved through st.file_uploader().

# Create file uploader objectupload_file = st.file_uploader('Upload a file containing earthquake data')

This little snippet of code does a lot of the heavy lifting when it comes to creating a way for users to upload files. When you add this and rerun the app, you get a nicely presented upload box, where you can manually browse for a file or drag and drop a file.

The file uploader dialogue using st.file_uploader(). Image by the author.

Once we have the file uploader setup, we now need to add some basic logic to detect when a file has been uploaded. If it has, then read the uploaded csv file.

if upload_file is not None:   # Read the file to a dataframe using pandas
df = pd.read_csv(upload_file)

All remaining code can now be placed indented and under this if statement. This way the subsequent code will not be run unless the file has been uploaded.

Display Pandas Describe and Data Within Streamlit

Accessing the df.describe() and df.head() methods from pandas is very simple. We wrap these functions inside of the st.write() method and all of the formatting will be sorted automatically.

# Create a section for the dataframe statistics
st.header('Statistics of Dataframe')
st.write(df.describe())
# Create a section for the dataframe header
st.header('Header of Dataframe')
st.write(df.head())

To test if this is working, select the CSV file (kaggle_significant_earthquakes_database.csv) from the Streamlit Tutorial Series GitHub repository and use the file uploader to upload it to the app.

Once the file has been uploaded the statistics of the data along with the first five rows should now be displayed.

Example of displaying pandas functions using the st.write method in streamlit. Image by the author.

Display a Matplotlib Figure With Streamlit

The final step for this simple app is to display a figure from matplotlib.

First, we need to define a figure and the axes. In this example I have assigned them to plt.subplots().

Under this, we can then create the plot, which will be a scatter plot of earthquake depth versus earthquake magnitude.

We then wrap the fig in st.pyplot().

fig, ax = plt.subplots(1,1)ax.scatter(x=df['Depth'], y=df['Magnitude'])
ax.set_xlabel('Depth')
ax.set_ylabel('Magnitude')
st.pyplot(fig)

When we go back to our app after it has been rerun we will now see the matplotlib figure.

Displaying a matplotlib figure using streamlit’s st.pyplot() function.

The figure that is returned is a standard matplotlib figure and does not feature any interactive functionality. Instead of using matplotlib, it is possible to use plotly to create interactive plots.

Full Code

Here is the full code to generate a very simple web app using the Streamlit library.

#Import the required Librariesimport streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
# Add a title and intro text
st.title('Earthquake Data Explorer')
st.text('This is a web app to allow exploration of Earthquake Data')
# Create file uploader object
upload_file = st.file_uploader('Upload a file containing earthquake data')
# Check to see if a file has been uploaded
if upload_file is not None:
# If it has then do the following: # Read the file to a dataframe using pandas
df = pd.read_csv(upload_file)
# Create a section for the dataframe statistics
st.header('Statistics of Dataframe')
st.write(df.describe())
# Create a section for the dataframe header
st.header('Header of Dataframe')
st.write(df.head())
# Create a section for matplotlib figure
st.header('Plot of Data')
fig, ax = plt.subplots(1,1)
ax.scatter(x=df['Depth'], y=df['Magnitude'])
ax.set_xlabel('Depth')
ax.set_ylabel('Magnitude')
st.pyplot(fig)

Here is the final web app generated with the code above. The app is very static and will only change when new files are uploaded.

Streamlit web based app to visualise earthquake data. Image by the author.

Within this short tutorial we have seen how to create a very simple web application with Streamlit. It allows us to load in data to our app and immediately display descriptive statistics and a matplotlib figure. The current app is static, meaning that the user will only see a static figure and the data with no interaction or updating of the code through parameters. This can easily be enhanced using selection boxes, plotly and many other Streamlit features.

If you want a handy little cheatsheet to use alongside Streamlit, then check out this one from the streamlit documentation.

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment