The Art of Data Applications with Streamlit in Python

Streamlit: The Artist of Data Applications in Python

Hello everyone, I am an experienced Python tutorial author. Today, I want to introduce you to a very practical Python library in the field of data application development—Streamlit. As a powerful tool, Streamlit provides a simple and efficient way to easily transform Python scripts into beautiful, interactive web applications. Whether you need to build data dashboards, visualize analytical reports, or develop interactive demonstration systems for machine learning models, Streamlit can provide you with an excellent development experience. Let’s explore the charm of Streamlit together!

The Art of Data Applications with Streamlit in Python

The Importance of Data Application Development

In today’s data-driven era, the rapid creation of data applications has become an urgent need in many industries. Whether it’s financial analysts needing to monitor market indicators in real time, scientists needing to visualize experimental results, or business managers needing to explore sales trends, they all require an efficient way to present and interact with data.

The traditional web development process is often complex and cumbersome, requiring developers to master multiple technologies simultaneously, such as front-end frameworks, back-end servers, databases, etc. For many Python developers, they focus more on data processing and analysis itself, hoping to concentrate on business logic without worrying too much about the deployment and interaction details of applications.

This calls for a simple and efficient tool that can quickly transform Python scripts into beautiful, interactive web applications, and Streamlit is an excellent choice.

Getting Started with Streamlit

Let’s understand the basic usage of Streamlit through a simple example. We will create a simple application to visualize some stock data.

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

# Load data
stock_data = pd.read_csv('stock_data.csv')

# Create Streamlit application
st.title('Stock Data Visualization')
st.write('Please select the stock code to visualize:')
stock_code = st.selectbox('', stock_data['code'].unique())

# Plot stock closing price trend
filtered_data = stock_data[stock_data['code'] == stock_code]
fig, ax = plt.subplots()
ax.plot(filtered_data['date'], filtered_data['close'])
ax.set_title(f'{stock_code} Closing Price Trend')
ax.set_xlabel('Date')
ax.set_ylabel('Closing Price')
st.pyplot(fig)

In this code, we first import the streamlit, pandas, and matplotlib modules. Then, we load a CSV file containing stock data.

Next, we use the st.title function to create an application title and the st.write function to add some text descriptions.

The next step is to use the st.selectbox function to create a dropdown box that allows users to select the stock code to visualize.

Then, we filter the corresponding stock data based on the user’s selection and use matplotlib to plot the closing price trend of the stock.

Finally, we use the st.pyplot function to embed this figure into the Streamlit application.

Tip: Streamlit supports various data sources, such as CSV, Excel, SQL databases, etc.

Interactive Controls and Layout

In addition to basic data visualization, Streamlit also provides rich interactive controls and layout options, allowing you to create more complex and dynamic applications. Let’s look at a more advanced example:

import streamlit as st
import pandas as pd

# Load data
iris_data = pd.read_csv('iris.csv')

# Create Streamlit application
st.title('Iris Data Exploration')
st.write('Use the sliders below to adjust data filtering conditions:')

# Add interactive controls
sepal_length_min = st.slider('Minimum Sepal Length', 4.0, 8.0, 4.0, 0.1)
sepal_length_max = st.slider('Maximum Sepal Length', 4.0, 8.0, 8.0, 0.1)
sepal_width_min = st.slider('Minimum Sepal Width', 2.0, 4.5, 2.0, 0.1)
sepal_width_max = st.slider('Maximum Sepal Width', 2.0, 4.5, 4.5, 0.1)

# Filter data
filtered_data = iris_data[
    (iris_data['sepal_length'] >= sepal_length_min) &
    (iris_data['sepal_length'] <= sepal_length_max) &
    (iris_data['sepal_width'] >= sepal_width_min) &
    (iris_data['sepal_width'] <= sepal_width_max)
]

# Display filtered results
st.write(f'There are {len(filtered_data)} rows of data that meet the criteria:')
st.dataframe(filtered_data)

In this example, we first load a CSV file containing the iris dataset.

Then, we use the st.title and st.write functions to create the application title and description text.

Next, we use the st.slider function to create four slider controls, which are used to adjust the filtering range for sepal length and width.

The next step is to filter the iris data based on the conditions set by the user through the sliders.

Finally, we use the st.write and st.dataframe functions to display the number of filtered results and the content of the dataframe.

Through this example, you can see that Streamlit provides powerful interactive controls and layout features, allowing you to easily create rich and dynamic data applications.

Practical Exercise

Let’s do a practical exercise and develop a simple machine learning model demonstration application using Streamlit!

  1. Select a beginner-friendly machine learning task, such as classification of the iris dataset or regression of Boston housing prices.
  2. Write a Python script to implement the following functionalities:
  • A text area for inputting prediction data
  • A button to trigger the model prediction
  • An area to display the model prediction results
  • Load and preprocess the data
  • Train the machine learning model
  • Create a Streamlit application that includes the following:
  • Further extend the application by adding the following features:
    • Allow users to select different machine learning algorithms
    • Add some interactive controls to adjust model hyperparameters
    • Add an area to display model evaluation metrics
  • Try using other features provided by Streamlit, such as file upload, state updates, etc.
  • I believe through this exercise, you will have a deeper understanding of how to use Streamlit.

    Conclusion

    Today, we learned how to use the powerful Python library Streamlit to quickly create beautiful, interactive data applications. Through this article, you have mastered the basic usage of Streamlit, as well as techniques for interactive controls and layout.

    The advantage of Streamlit lies in its ability to provide a simple and efficient way to easily transform Python scripts into web applications, greatly improving our data application development efficiency.

    I encourage you to continue exploring more powerful features of Streamlit, such as multi-page applications and component caching. At the same time, also pay attention to learning some best practices for web application development to ensure that your code is readable and maintainable.

    If you encounter any problems during the learning process, feel free to consult me. I believe that through continuous learning and practice, you will become an outstanding data application developer. Let’s work together and strive for success!

    Leave a Comment