Building Interactive Data Science Web Apps with Streamlit: A Comprehensive Guide
As data science and machine learning become increasingly important across industries, there is a growing need for tools that allow data scientists to quickly build and share interactive web applications. Traditional web development can be time-consuming and requires specialized skills, creating friction in the fast-paced workflow of data science teams.
Enter Streamlit, an open-source Python library that makes it easy to create beautiful, performant apps for machine learning and data science. With Streamlit, you can build a complete web app in just a few dozen lines of Python code. No front-end experience required.
In this guide, we‘ll dive deep into Streamlit and learn how you can use it to build powerful data science web applications with ease. Whether you‘re a data science beginner or a seasoned pro, by the end of this post you‘ll be equipped with the knowledge and skills to build your own Streamlit apps.
What is Streamlit?
At its core, Streamlit is a Python library that provides a simple API for creating web apps. It allows you to write an app the same way you write a Python script – with Python code, not HTML and JavaScript.
Some key features of Streamlit include:
- Built-in components for displaying text, charts, tables, and more
- Easy integration with popular data science libraries like NumPy, Pandas, Matplotlib, etc.
- Support for caching, which enables fast performance even with large datasets
- Ability to interact with visualizations, select parameters, and re-run models in real-time
- Effortless deployment with platforms like Heroku, AWS, and Google Cloud
Under the hood, Streamlit uses Tornado and React to render the app interface and handle user interaction. But as a developer, you just write simple Python scripts and let Streamlit take care of the rest.
Compared to other frameworks for building data web apps like Dash or Bokeh, Streamlit aims to be simpler and more tightly integrated with the Python data science ecosystem. It has gained significant popularity, with over 20,000 stars on GitHub as of 2023.
Setting Up Streamlit
Before we start building Streamlit apps, let‘s go through the setup process. The only prerequisite is that you have Python 3.7 or later installed.
To install Streamlit, simply run:
pip install streamlit
Once the installation is finished, you can test it out by running:
streamlit hello
This will open up the Streamlit Hello World app in your default web browser. Now you‘re ready to start developing your own apps!
For more detailed instructions, check out the official Streamlit documentation: https://docs.streamlit.io/
Anatomy of a Streamlit App
A Streamlit app is just a Python script that contains Streamlit-specific functions. Here‘s a minimal example:
import streamlit as st
st.title(‘My First Streamlit App‘)
st.write(‘Hello, World!‘)
Let‘s break this down:
- First, we import the streamlit library, usually aliased as st
- st.title() displays a page title
- st.write() can display text, data frames, plots, and more
To run this app, save it as a Python file (e.g. app.py) and execute:
streamlit run app.py
Streamlit will automatically launch the app in a new browser tab for you to interact with. Any time you modify the code, just save the file and Streamlit will detect the change and ask if you want to rerun the app.
This is the basic structure that all Streamlit apps will follow. Now let‘s explore some of the key building blocks you‘ll use to create more complex apps.
Display Text and Markdown
In addition to st.title() and st.write(), there are a number of other ways to display text:
st.header(‘This is a header‘)
st.subheader(‘This is a subheader‘)
st.caption(‘This is a caption‘)
st.markdown(‘This is **bold** and *italic* text‘)
st.latex(r‘‘‘ a + b = c ‘‘‘)
Display Data
Streamlit makes it simple to display data in your app, whether it‘s in a data frame, table, chart, or other format.
To display a Pandas DataFrame, just pass it to st.write() or use st.dataframe():
import pandas as pd
df = pd.read_csv(‘data.csv‘)
st.dataframe(df)
Similarly, you can display tables, metrics, JSON data, and more.
Widgets and User Input
To make your app interactive, Streamlit provides a variety of input widgets like buttons, sliders, checkboxes, and text inputs. Here are a few examples:
# Display a button
if st.button(‘Click me‘):
st.write(‘You clicked the button!‘)
# Display a slider
x = st.slider(‘Select a value‘, 0, 100, 50)
st.write(f‘You selected: {x}‘)
# Display a checkbox
if st.checkbox(‘Show data‘):
st.write(df)
# Display a radio button
animal = st.radio(‘What is your favorite animal?‘,
(‘Dog‘, ‘Cat‘, ‘Bird‘))
# Display a text input
name = st.text_input(‘Enter your name‘, ‘‘)
st.write(f‘Hello {name}‘)
When an input widget is changed by the user, the app will rerun from top to bottom. This allows you to write declarative, reactive code that responds to user input.
Visualize Data
Of course, one of the most powerful features of Streamlit is the ability to create interactive data visualizations. Streamlit integrates seamlessly with popular charting libraries like Matplotlib, Altair, Plotly, Bokeh, and more.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [1, 2, 3])
st.pyplot(fig)
Pass your chart to st.pyplot(), st.altair_chart(), st.plotly_chart() etc. depending on which library you‘re using. Streamlit will automatically display it in the app.
You can also create more complex dashboards by combining multiple charts and widgets. Use st.columns() to arrange elements side by side.
col1, col2 = st.columns(2)
with col1:
st.header("A dog")
st.image("https://images.dog.ceo/breeds/shiba/shiba-8.jpg", use_column_width=‘always‘)
with col2:
st.header("A cat")
st.image("https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg", use_column_width=‘always‘)
Advanced Features
So far we‘ve covered the basics, but Streamlit offers a number of more advanced features to take your apps to the next level:
Caching
If your app performs any expensive computations, you‘ll want to use caching to avoid rerunning them unnecessarily. Just add the @st.cache decorator to your function:
@st.cache
def expensive_computation(a, b):
return a * b
Now the function will only rerun when the inputs change. Streamlit takes care of the rest.
Custom Components
While the built-in components cover most use cases, sometimes you need something more customized. For this, Streamlit recently introduced support for custom components using HTML, CSS, and JavaScript.
See this tutorial for details: https://blog.streamlit.io/introducing-streamlit-custom-components-and-streamlit-0-76/
Theming
You can customize the look and feel of your Streamlit app by modifying the theme. This includes colors, font, page layout, and more.
To set the theme, just call st.set_page_config() at the start of your app:
st.set_page_config(page_title="My App",
page_icon=":smiley:",
layout="wide",
initial_sidebar_state="expanded")
Streamlit also provides a number of built-in themes you can use with st.set_theme().
Example Streamlit Apps
To get a sense of what‘s possible with Streamlit, let‘s look at a few examples of real-world apps:
-
Molecular Playground (https://molplayground.org/): An interactive app for exploring molecular structures and properties. Uses RDKit and 3DMol.js for cheminformatics and 3D visualization.
-
COVID-19 Dashboard (https://www.streamlit.io/gallery): A dashboard for tracking COVID-19 cases and trends. Pulls data from an API and displays it using charts and maps.
-
Face GAN (https://face-gan.herokuapp.com/): A face generator app powered by a GAN (generative adversarial network) model. Users can tweak parameters and generate new faces.
-
SpacyIO (https://spacyio.streamlit.app/): A collection of demos and visualizers for the spaCy NLP library. Includes named entity recognition, dependency parsing, similarity, and more.
These just scratch the surface of what people are building with Streamlit. For more examples and inspiration, check out the official Streamlit Gallery: https://streamlit.io/gallery
Deployment and Sharing
Once you‘ve built your Streamlit app, the final step is to deploy it so others can use it. Streamlit offers a few different options:
-
Streamlit Sharing: A free hosting service provided by Streamlit. Just create an account, upload your code, and your app will be live on the web. Includes GitHub integration.
-
Deploy to Heroku: Package your app as a Docker container and deploy it to Heroku. See this guide: https://towardsdatascience.com/quickly-build-and-deploy-an-application-with-streamlit-988ca08c7e83
-
Deploy to AWS/GCP/Azure: For more control and scalability, deploy your Streamlit app on a cloud platform like AWS, Google Cloud, or Microsoft Azure. This requires more setup but offers flexibility.
You can also run your app locally and use a tool like ngrok to create a public URL for sharing.
Streamlit Resources
Here are some of the best resources for learning more about Streamlit and taking your skills to the next level:
- Official Streamlit Docs: https://docs.streamlit.io/
- Streamlit Gallery: https://streamlit.io/gallery
- Awesome Streamlit (GitHub Repo): https://github.com/MarcSkovMadsen/awesome-streamlit
- "How to Master Streamlit for Data Science" (Medium article): https://towardsdatascience.com/how-to-master-streamlit-for-data-science-d3a39a3c5d93
- "Building a Streamlit Component" (Blog post): https://blog.streamlit.io/building-a-streamlit-component-from-scratch-a-step-by-step-tutorial/
There are also a number of excellent video tutorials and courses available on platforms like YouTube and Udemy.
The Future of Streamlit
As of 2023, Streamlit has established itself as one of the go-to tools for rapid web app development in the data science community. But the library is still actively evolving, with regular updates and new features being added.
Some exciting developments on the horizon include:
- Streamlit Components 2.0: An improved framework for building custom components
- Better support for app deployment and collaboration
- More customization options for app layout and style
- Integration with additional data science libraries and frameworks
It‘s also likely that we‘ll see growing adoption of Streamlit beyond just the data science niche. The simplicity and flexibility of the library make it appealing for general web app development as well.
At the same time, Streamlit will face increasing competition from similar tools like Dash, Panel, Voilà, and others. It will be interesting to see how the ecosystem evolves and which tools emerge as the leaders.
Conclusion
Streamlit is a powerful tool that is revolutionizing the way data scientists build and share web apps. With its simple, Python-centric API and rich feature set, it enables developers to focus on their data and models while letting Streamlit handle the app infrastructure.
Whether you‘re building a simple prototype or a production-grade application, Streamlit likely has the functionality you need. And the library is only getting better over time.
In this guide, we‘ve covered everything you need to know to start building your own Streamlit apps. We‘ve explored the key concepts, walked through practical examples, and discussed strategies for deployment and sharing.
Now it‘s up to you to put this knowledge into practice. Use Streamlit to build that interactive data explorer you‘ve been dreaming of, create a sleek dashboard for your machine learning project, or prototype a whole new app idea from scratch.
The possibilities with Streamlit are endless. Get out there and start creating!