DEV Community

Cover image for A Beginner's Guide to Making Data Web Applications using Python with Streamlit

A Beginner's Guide to Making Data Web Applications using Python with Streamlit

This article is co-authored by Jed Franz M. Romero.

As a Python programmer, you usually work with different kinds of data most of the time. At the same time, Python developers usually work on the server side or the backend on a lot of projects. But have you ever wondered if you could share your data easily on a web application for other users to see, without needing to have frontend development skills? Let us introduce you to a Python framework that is simple and beginner-friendly: Streamlit!

What is Streamlit?

Streamlit is an open-source Python framework that is used just like any Python library. It provides a way to share and display different data simply through web applications, all purely in Python. It is basically a frontend cheat code for Python developers who want to create web applications in a fast and simple way. It provides several unique functionalities, including simple writing of text, data elements, charts, input widgets, media elements, layouts and containers, chat elements, and status elements.

Why use Streamlit?

A lot of web application projects use Python for the backend with HTML and CSS or even other frontend frameworks for the frontend. However, using HTML, CSS, and other frameworks is usually difficult to use, as they have long syntaxes and can result in many lines of code. Streamlit helps developers, especially with rushed projects, to create web applications efficiently. Although it is a framework that uses Python, it can translate Python code into a web user interface. As Python can already handle different types of data, Streamlit helps share and display that data.

Just like any Python library, it can easily be installed in your projects. It provides very simple syntax for its elements, just like a simple function call with several parameters to adjust its characteristics. It is simple and clean, which improves your code’s readability. It is also a very helpful playground, as changes in your code will automatically refresh your web application, whether it is running on your local machine or on your preferred deployed environment. Furthermore, Streamlit also provides free deployment of your Streamlit applications on their community cloud, which allows a lot of developers to share their data and ideas with users from all around the world.

Getting Started with Streamlit

As we begin with learning all about Streamlit in Python, let us first prepare and install everything that we need for our project.

Prerequisites

Before we begin, it is important to check if you have a proper setup for Streamlit to work. For this guide, make sure you have the following:

  1. Python 3.9 or higher (you can check by typing the command python --version or python3 --version in a terminal),
  2. a Python package manager such as pip, and
  3. a code editor of your choice.

Installation

Before we begin, we must first create a folder or directory where we will make our project. Open any terminal and type in:

mkdir myFirstStreamlitApp
Enter fullscreen mode Exit fullscreen mode

Next, we must redirect our machines to our project directory, where we want Streamlit to be installed. Open any terminal and go to your project directory by typing the command below:

cd myFirstStreamlitApp
Enter fullscreen mode Exit fullscreen mode

Once in the project directory, it is recommended to create a Python virtual environment for your project in order to keep what you install inside your project, rather than globally in your computer. You can setup a virtual environment by typing the command below:

python -m venv .venv
Enter fullscreen mode Exit fullscreen mode

Then, you must activate your virtual environment with the command below:

# Windows Command Prompt
.venv\Scripts\activate.bat

# Windows Powershell
.venv\Scripts\Activate.ps1

# macOS or Linux
source .venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Once your virtual environment is up and running, you can now install the Streamlit package by typing the following command:

pip install streamlit
Enter fullscreen mode Exit fullscreen mode

To test if you’ve installed it properly, run the following command to see the official Streamlit app locally:

streamlit hello
Enter fullscreen mode Exit fullscreen mode

Once a website is opened in your browser locally, you’ve completed the installation of Streamlit.

Screenshot of the opened Streamlit app after entering 'streamlit' hello

How to run your Streamlit app

In order to open your Streamlit app, you must always run your virtual environment. Create a Python file app.py where you will write Streamlit functions to handle your data. The following command allows you to open and test your app locally:

streamlit run app.py
Enter fullscreen mode Exit fullscreen mode

This will run and open your app locally in your browser (usually at localhost:8501), ready for editing and sharing.

Import Streamlit

In order to access Streamlit in your Python files, you will need to import it on top of the files.

import streamlit as st
Enter fullscreen mode Exit fullscreen mode

This will allow you to use Streamlit with st with any function, just like st.write().

Import Data

To follow along with the tutorial, download all of the CSV files in this Google Drive, and place them in your project folder. These files serve as our sample data which we will be using for the examples below.

Once in the project folder, you can then create a dataframe from the CSV by writing the following code. Note: To create a dataframe from a CSV file, you will need the help of pandas.

import pandas as pd

preference_dataframe = pd.read_csv("preference_data.csv")
summary_matrix = pd.read_csv("preference_summary.csv")
visitor_dataframe = pd.read_csv("visitor_data.csv")
plant_dataframe = pd.read_csv("plant_data.csv")
sales_dataframe = pd.read_csv("sales_data.csv")
Enter fullscreen mode Exit fullscreen mode

Using Streamlit functions

Now we are at the exciting part! Let us try to share and display different types of data using the different functions Streamlit provides.

The functions allow us to create basic text elements such as st.title(), st.header(), and st.text(), and data visualizations, some of which we will explore in the following examples.

Example 1: st.dataframe()

We can display our imported raw data in two different ways. One of which is through the function st.dataframe(), which displays your dataframe as an interactive table. This allows users to view and explore your data in various ways, such as sorting, reordering, resizing, copying, and downloading data.

For this example, let us display our preference data as an interactive table. To create an interactive table, type the code below:

st.header("Interactive Table")
st.dataframe(preference_dataframe)
Enter fullscreen mode Exit fullscreen mode

Sample interactable table using st.dataframe()

Once your code is running, your browser should now display the given dataframe in an interactive table.

Example 2: st.table()

Another way to display our raw data is using st.table(). This can be used when you want to have a static table instead of an interactive table.

For this example, let us try to display our sample summary report of our preference data as a static table. To create a static table, type the code below:

st.header("Static Table")
st.table(summary_matrix)
Enter fullscreen mode Exit fullscreen mode

Once written, your web application will display the summary report of the data through a simple and static table.

Sample static table using st.table()

Example 3: st.metric()

If you want to present a metric or a value that is being tracked over time, we can show it using st.metric(). This function lets you display a value and how much it has changed over time.

In this example, let us try to show the last recorded visitor count from our visitor dataframe (obtained by using visitor_dataframe["Count"].iloc[-1]) as a metric and compare its difference with the previous record (obtained by using visitor_dataframe["Count"].iloc[-2]). To do this, type the code below:

last_recorded = visitor_dataframe["Count"].iloc[-1]
previous_recorded = visitor_dataframe["Count"].iloc[-2]

value = last_recorded
delta = last_recorded - previous_recorded

st.header("Metric")
st.metric("Visitors", value, delta, border=True)
Enter fullscreen mode Exit fullscreen mode

Sample metric using st.metric()

The st.metric() function takes multiple parameters. The first parameter, label, describes the header of the metric. The second parameter, value, describes the value of the metric. The third parameter, delta, describes the amount of how much the value has changed. Other parameters help change the appearance and behaviour of the metric element, such as label_visibility and border.

Example 4: st.bar_chart()

A bar chart is a graphical representation to see the differences between different categories.

For example, we want to see the difference in the heights of plants graphically. To do that, we will create a simple bar chart. To create one with the help of Streamlit, type the function element below:

st.header("Bar Chart")
st.bar_chart(plant_dataframe, x="Plant", y="Height (in cm)")
Enter fullscreen mode Exit fullscreen mode

Once written in your code, the bar chart will show up in your web application when run. You will see a bar chart representing plant data.

Sample bar chart using st.bar_chart()

The st.bar_chart() function provides several parameters to be handled. The first one defines the dataframe to be displayed. The second parameter defines the x-axis value, which is the different types of plants listed in our data. Similarly, the third parameter defines the y-axis value, which is specified as the height of the plants in centimeters. It also handles other parameters like x_label, y_label, color, horizontal, sort, stack, width, and height.

Example 5: st.line_chart()

A line chart is a graphical representation of trends or changes in data.

Given the data of the monthly sales of a business, let us try to display it using a line chart to see how the sales of the business changed throughout the year.

First, we should remember that different data must be handled differently. As in this case, you need to check how the month is formatted, whether it be in the format of “Month” or “Year-Month” as the line chart function will treat them differently. To handle these sorts of challenges, you will need to ask for help from another library such as pandas. One way to do this is to include the code below:

sales_dataframe['Month'] = pd.to_datetime(sales_dataframe['Month'], format="%Y-%b")
sales_dataframe = sales_dataframe.sort_values('Month')
Enter fullscreen mode Exit fullscreen mode

Then to create a line chart, type the function below.

st.header("Line Chart")
st.line_chart(sales_dataframe, x="Month", y="Sales")
Enter fullscreen mode Exit fullscreen mode

Once coded, you will see the line chart in your web application.

Sample line chart using st.line_chart()

The st.line_chart() function also provides several parameters to be handled. Similarly, one parameter is the x-axis, which in this case is the months, while another parameter is the y-axis, which in this case is the sales. Other parameters also include x_label, y_label, color, width, and height.

Conclusion

Congratulations! You have made your first data web app using Streamlit. Now that you have explored some of Streamlit’s features, you can further enhance your data web apps with its other features, such as creating layouts, adding media elements, using input widgets, adding pagination, caching, authentication, integrating other Python libraries and frameworks like matplotlib or Pytorch, and many more. You can also start sharing your data apps by deploying your Streamlit script in your own preferred deployment environment or even in Streamlit Community Cloud for free.

In case you need more inspiration as to how Streamlit can be used to make web apps, you can visit Streamlit’s app gallery or the Streamlit Community Cloud to check other people’s projects with Streamlit. You can also check the official documentation website to learn more about its features and its inner workings.

If you want to further explore the code snippets above, you can access the source code in its GitHub repository.

You can also visit a working demo of the code on this website hosted in Streamlit Community Cloud.

References:

Top comments (0)