Understanding Streamlit
Streamlit is an open-source Python library that makes it straightforward to create custom web applications for machine learning and data science. Launched in 2019, it addresses a significant pain point in the data science process: transforming code and data into interactive applications.
Getting Started
To use Streamlit, install the library via pip:
pip install streamlit
Once installed, you can start a new Streamlit app by writing a Python script. A minimal script might look like this:
import streamlit as stst.title('Hello, Streamlit!')st.write('This is my first Streamlit app.')
Run the script with the following command:
streamlit run your_script.py
This command will launch a local server and open a new tab in your default web browser showing the app.
Core Features
Streamlit provides simple commands to display various elements:
- Text and Markdown: Use
st.write()
for basic text andst.markdown()
for styled text. - DataFrames: Leverage
st.dataframe()
to display Pandas DataFrames interactively. - Plots: Use libraries like Matplotlib, Seaborn, or Plotly within
st.pyplot()
andst.plotly_chart()
. - Widgets: Interact with your audience using sliders, buttons, and selectboxes.
Text and Markdown
Displaying text is simple with Streamlit. For instance:
st.write('Hello, World!')st.markdown('# This is a markdown header')
Text elements automatically adjust based on the displayed content.
Displaying DataFrames
DataFrames can be presented with a scrollable and sortable interface:
import pandas as pddata = {'Column1': [1, 2, 3], 'Column2': [4, 5, 6]}df = pd.DataFrame(data)st.dataframe(df)
This displays the DataFrame in a user-friendly way.
Plotting
Use your favorite plotting libraries without much setup:
import matplotlib.pyplot as pltfig, ax = plt.subplots()ax.plot([1, 2, 3], [4, 5, 6])st.pyplot(fig)
Streamlit supports integration with Plotly and other libraries for advanced visualizations.
Widgets
Interactive widgets like sliders and buttons enhance app interactivity:
age = st.slider('Select your age', 0, 100, 25)st.write('Your age is', age)
Information entered into widgets can be used for real-time data updates and interactions.
Layouts and Customization
- Containers: Use
st.container()
to group elements. - Columns: Create multi-column layouts with
st.columns()
. - Expander: Collapsible sections with
st.expander()
.
Using Containers
Group several elements together in a container:
with st.container(): st.write(Contained within a box)st.write(Outside the container)
This makes organization easier and more visually appealing.
Multi-column Layouts
Multiple columns can present data side-by-side:
col1, col2 = st.columns(2)col1.write(This is column 1)col2.write(This is column 2)
Use columns to structure more complex layouts.
Expandable Sections
Make sections expandable for a cleaner interface:
with st.expander('Expand me'): st.write('Hidden content!')
Expander widgets can streamline the user interface by hiding less pertinent information.
Advanced Features
Streamlit allows for caching, state management, and theming.
- Caching: Speed up the app by caching expensive functions with
@st.cache
. - State Management: Use
st.session_state
to manage variables across sessions. - Custom Themes: Introduce custom themes in the
.streamlit/config.toml
file.
Caching Functions
Reduce computational load by caching results:
@st.cachedef expensive_function(): time.sleep(2) # Simulate a long computation return 42result = expensive_function()st.write(result)
This makes the app more responsive, especially for repeated calculations.
Session State
Maintain state information even after interactions:
if 'count' not in st.session_state: st.session_state.count = 0if st.button('Increment'): st.session_state.count += 1st.write(st.session_state.count)
Session state enables the creation of more dynamic and interactive applications.
Custom Themes
Customize the look of your app by editing the configuration file:
[theme]primaryColor = '#1f77b4'backgroundColor = '#f0f0f5'secondaryBackgroundColor = '#e0e0ef'textColor = '#262730'
This extends the visual customizability beyond default settings.
Deployment
Streamlit apps can be deployed using platforms like Heroku, AWS, and Streamlit Sharing. Streamlit Sharing is the official platform endorsed by the Streamlit team for easy deployment. It provides a straightforward way to share your apps by linking to a GitHub repository. Here’s a brief overview of the deployment process using Streamlit Sharing:
- Push your Streamlit app script to a GitHub repository.
- Log in to Streamlit Sharing and create a new app by linking to your repository.
- Streamlit Sharing will automatically deploy your app and provide a shareable URL.
For deployment on other platforms, Docker containers or web server configuration might be necessary, but clear documentation and community support are readily available.
“`