article cover
Badreddine Chaguer

Badreddine Chaguer

Senior Data scientist/Co-founder

Streamlit in 15 Minutes: Turn Python Scripts into Interactive Web Apps

October-02-2024

Streamlit is an open-source framework that allows you to quickly create interactive web applications with Python, without needing any front-end development skills. It's a powerful tool for visualizing data, building dashboards, and easily sharing your analysis.

In this blog, we'll explore the basics of Streamlit, how to install it, and how to develop a simple app using Python code.

Installing Streamlit

Before getting started, ensure that Python is installed on your machine. To install Streamlit, run the following command in your terminal:

pip install streamlit

Once installed, you can verify that everything works by running the following command:

streamlit hello

This will open a demo application in your web browser.

Building Your First Streamlit App

Let's start with a basic app that displays text and an interactive chart.

1. Displaying Simple Text

Create a Python file, for example, app.py, and write the following code:

import streamlit as st

# App title
st.title('Hello, Welcome to Your First Streamlit App!')

# Subtitle
st.subheader('A Simple Web App Using Streamlit')

# Descriptive text
st.write('This is an example of displaying text with Streamlit.')

To run the app, simply type the following command in your terminal:

streamlit run app.py

This will open your app in a browser window, displaying the text you defined.

2. Adding a Plot with Matplotlib

Streamlit integrates easily with visualization libraries such as Matplotlib and Seaborn. Let’s create a simple plot using Matplotlib:

import matplotlib.pyplot as plt
import numpy as np
import streamlit as st

# Title
st.title('Interactive Plot with Matplotlib')

# Data for the plot
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create the plot
fig, ax = plt.subplots()
ax.plot(x, y)

# Display the plot in Streamlit
st.pyplot(fig)

Here, we use numpy to generate data and matplotlib to visualize it. Streamlit displays the plot using the st.pyplot() function.

3. Adding Interactivity

Streamlit allows you to add interactive elements such as sliders, checkboxes, and buttons to make your applications more dynamic.

Let’s add a slider that controls the amplitude of the sine wave in our plot:

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

# Title
st.title('Interactive Sine Wave Plot')

# Slider to control amplitude
amplitude = st.slider('Amplitude', min_value=0.0, max_value=10.0, value=1.0)

# Data for the plot
x = np.linspace(0, 10, 100)
y = amplitude * np.sin(x)

# Create the plot
fig, ax = plt.subplots()
ax.plot(x, y)

# Display the plot
st.pyplot(fig)

With this code, users can adjust the sine wave’s amplitude using the slider, and the plot will automatically update.

4. Loading and Displaying Data

Streamlit is also excellent for displaying and interacting with datasets. Suppose you have a CSV file with data, you can easily load and display it in the app.

Let’s add a file uploader to upload and visualize a CSV file:

import streamlit as st
import pandas as pd

# Title
st.title('Upload and Display Data')

# File uploader
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")

# Check if a file has been uploaded
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write("Preview of the uploaded data:")
    st.write(data.head())  # Display the first few rows of the file

This code allows users to upload a CSV file from their computer, and Streamlit will display a preview of the first few rows.

5. Dynamic Data Filtering Application

Finally, we can add dynamic filters for the data. For example, suppose you have a dataset about flowers (like the Iris dataset), you can allow users to filter data based on a specific column.

import streamlit as st
import seaborn as sns
import pandas as pd

# Load the Iris dataset
iris = sns.load_dataset("iris")

# Title
st.title('Dynamic Data Filtering')

# Dropdown to select a flower species
species = st.selectbox('Select a species', iris['species'].unique())

# Filter the data based on the selected species
filtered_data = iris[iris['species'] == species]

# Display the filtered data
st.write(filtered_data)

In this example, the user can select a flower species using a dropdown, and Streamlit will display only the rows that correspond to that species.

Conclusion

Streamlit is an incredibly convenient tool for quickly turning Python scripts into interactive web applications. With just a few lines of code, you can create intuitive user interfaces, interactive charts, and dynamic dashboards.

Here are some additional Streamlit features you can explore:

  • Integration with Plotly, Altair, and other visualization libraries.
  • Easy sharing of applications via Streamlit Cloud.
  • Creating interactive forms.

Feel free to explore further and integrate Streamlit into your projects to make your data analysis more interactive and accessible!

Master AI Tools in Just 5 Minutes a Day

Join 1000+ Readers and Learn How to Leverage AI to Boost Your Productivity and Accelerate Your Career

Newsletter language