Streamlit Tutorial: Building Web Apps with Python

Streamlit is a powerful open-source framework for quickly building data science and machine learning web apps using Python. It allows data scientists and ML engineers to create interactive apps with only a few lines of code, no front-end experience required.

Streamlit provides a simple way to create web interfaces for your projects by writing Python scripts. It takes care of the web development details behind the scenes so you can focus on your data and models.

In this tutorial, we‘ll cover everything you need to know to start building Streamlit web apps. We‘ll go over the key features, walk through code examples of all the major components, and build an interactive demo app step-by-step. Let‘s get started!

Installing Streamlit

First, make sure you have Python 3.7 – 3.10 installed. Then install Streamlit using pip:

$ pip install streamlit

Streamlit is now installed and ready to use. To make sure everything is working, run:

$ streamlit hello

This will open the Streamlit Hello app in a new browser tab. The Hello app is a great overview of what you can build with Streamlit.

Creating a Streamlit App

With Streamlit installed, we‘re ready to start building apps. Create a new Python file called app.py (or any name you like). This is the main entry point for the Streamlit app.

Open app.py in your code editor and add the following:

import streamlit as st

st.title(‘My First Streamlit App‘)

st.write(‘Hello, World!‘)

This imports the Streamlit library, displays a page title, and prints "Hello, World!" to the page. To run the app, use the Streamlit CLI:

$ streamlit run app.py

Streamlit will start a local web server and open your app in a new browser tab. That‘s it – you‘ve built your first Streamlit app! Let‘s dive into more features and examples next.

Core Streamlit APIs and Widgets

Streamlit provides a variety of APIs and widgets for displaying data, collecting input from users, and controlling app logic flow. Let‘s go through the key UI elements with code samples.

Text Elements

Streamlit has several methods for displaying text:

import streamlit as st

st.title(‘This is a title‘)
st.header(‘This is a header‘)
st.subheader(‘This is a subheader‘)
st.text(‘This is plain text‘)
st.markdown(‘This is _markdown_‘) 
st.latex(r‘‘‘ a + b = c ‘‘‘)
st.code(‘x = 2\ny = 3\nprint(x + y)‘)

This displays a title, header, subheader, plain text, markdown (with italics), a LaTeX equation, and a code block.

Data Display Elements

Streamlit makes it easy to display data in your app:

import streamlit as st
import pandas as pd

st.dataframe(pd.DataFrame({‘col1‘: [1,2,3], ‘col2‘: [4,5,6]}))

st.table(pd.DataFrame({‘col1‘: [1,2,3], ‘col2‘: [4,5,6]}))

st.json({‘foo‘:‘bar‘,‘baz‘:[‘cat‘,12,345.67]})

st.metric(‘My Metric‘, 42) 

This displays a Pandas dataframe and table, a JSON object, and a single number with a delta.

Chart Elements

Streamlit supports many popular charting libraries for data visualization:

import streamlit as st
import pandas as pd

chart_data = pd.DataFrame(
  np.random.randn(20,3),
  columns=[‘a‘,‘b‘,‘c‘])

st.line_chart(chart_data)

st.area_chart(chart_data)

st.bar_chart(chart_data)

st.pyplot(plt.plot(chart_data))

st.plotly_chart(px.scatter(chart_data, x=‘a‘, y=‘b‘)) 

st.map(pd.DataFrame({‘lat‘:[50,51],‘lon‘:[-1.5,-0.5]}))

This creates a line chart, area chart, bar chart, matplotlib plot, plotly scatter plot, and a map with location points. You can easily create interactive visualizations in just a few lines of code.

Input Widgets

Next let‘s look at input widgets for collecting data from the user:

import streamlit as st

st.button(‘Click me‘)

st.checkbox(‘I agree‘) 

st.radio(‘Pick one‘, [‘cats‘, ‘dogs‘])

st.selectbox(‘Pick one‘, [‘cats‘, ‘dogs‘])

st.multiselect(‘Buy‘, [‘milk‘, ‘apples‘, ‘bread‘])

st.slider(‘Pick a number‘, 0, 100)

st.select_slider(‘Pick a size‘, [‘S‘, ‘M‘, ‘L‘])

st.text_input(‘First name‘)

st.number_input(‘Pick a number‘, 0, 10)

st.text_area(‘Text to translate‘)

st.date_input(‘Your birthday‘)

st.time_input(‘Meeting time‘)

st.file_uploader(‘Upload a CSV‘)

st.camera_input(‘Take a picture‘) 

st.color_picker(‘Pick a color‘) 

This shows a button, checkbox, radio buttons, select box, multiselect, slider, select slider, text input, number input, text area, date and time inputs, file uploader, camera input, and color picker.

Input widgets return a value based on the user‘s action. You can store the result in a variable and use the input later in your app.

Media Elements

Streamlit supports images, audio and video:

import streamlit as st

st.image(‘image.png‘)

st.audio(‘audio.mp3‘)

st.video(‘video.mp4‘) 

You can specify a caption, size, and other parameters for media elements.

Layout Elements

Streamlit has a few layout options:

import streamlit as st

# Sidebar
st.sidebar.header(‘Input‘)
a = st.sidebar.slider(‘a‘)
b = st.sidebar.slider(‘b‘)
st.write(a * b)

# Columns  
col1, col2 = st.columns(2)
with col1:
  st.header("A dog")
  st.image("https://static.streamlit.io/examples/dog.jpg")
with col2:
  st.header("A cat")
  st.image("https://static.streamlit.io/examples/cat.jpg")

# Tabs
tab1, tab2 = st.tabs(["Tab 1", "Tab 2"])
with tab1:
  st.header("Content for tab 1")
with tab2:
  st.header("Content for tab 2")

# Expander        
with st.expander("Click to expand"):
  st.write("Some hidden content")

This puts an input in the sidebar, creates a 2-column layout with images, organizes content in tabs, and hides content in an expander. You can use these layout elements to organize your app content.

Building an Interactive Dashboard

Now let‘s put this all together and create an interactive dashboard. We‘ll build an app that displays sales data and lets the user filter the results.

Create a file called sales_dashboard.py:

import streamlit as st
import pandas as pd

# Data
data = pd.DataFrame({
  ‘customer_id‘: [0,1,2,0,1,2],  
  ‘product‘: [‘A‘,‘B‘,‘C‘,‘A‘,‘B‘,‘D‘],
  ‘amount‘: [4, 6, 10, 6, 4, 5]
})

# Sidebar inputs
st.sidebar.header("Inputs")
selected_id = st.sidebar.selectbox(
  "Select a customer ID",
  data[‘customer_id‘].unique())

selected_products = st.sidebar.multiselect(
  "Select products", 
  data[‘product‘].unique())

# Main panel  
st.header("Customer Order Dashboard")  

# Dataframe filter  
filtered_df = data[
  (data[‘customer_id‘] == selected_id) & 
  (data[‘product‘].isin(selected_products))
]

st.dataframe(filtered_df)

# Bar chart
prod_sales = filtered_df.groupby(‘product‘)[‘amount‘].sum()  
st.bar_chart(prod_sales)

# Line chart
st.line_chart(filtered_df.groupby(‘product‘)[‘amount‘].sum())  

Run this app and interact with the dropdowns in the sidebar. The charts and data will update based on the selected customer and products.

This simple example shows how you can create interactive apps by storing user input in variables and using them to dynamically filter, aggregate, and visualize data.

You can expand this concept to build dashboards, machine learning demos, and other data apps. Streamlit lets you quickly spin up UIs so you can focus on the data science.

Deploying Streamlit Apps

When your app is ready to share, you can deploy it in a few ways:

  1. Use a cloud service like Streamlit Community Cloud to deploy for free
  2. Deploy to Heroku or AWS
  3. Run the app on your own server or machine

The Streamlit Community Cloud is the fastest way to get your app online. You can deploy directly from a GitHub repo or upload files from your machine.

To deploy an app, sign in to share.streamlit.io and click ‘New app‘. Select your repo, branch, and file path, then click ‘Deploy‘. Streamlit will build your app and give you a URL you can share with others. Apps auto-update when you push changes to GitHub.

Self-deploying to Heroku or hosting on your own infrastructure gives you more control but requires dev ops knowledge. Streamlit has guides for all the deployment options in their docs.

Resources and Next Steps

I hope this tutorial gave you a good foundation for building Streamlit apps. There‘s much more you can do – I encourage you to explore the API docs, Streamlit Gallery, and example apps.

Some ideas to try:

  • Build an app to explore a dataset
  • Visualize model results or evaluation metrics
  • Create an interactive ML demo that lets users tweak parameters
  • Port an existing Jupyter notebook analysis to Streamlit

The community is also a great resource – check out the forums for inspiration and help.

Happy Streamlit-ing! Let me know what you build.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts