The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to your script and save, Streamlit's UI will ask if you'd like to rerun the app and view the changes. This allows you to work in a fast interactive loop: you write some code, save it, review the output, write some more, and so on, until you're happy with the results. The goal is to use Streamlit to create an interactive app for your data or model and along the way to use Streamlit to review, debug, perfect, and share your code.
Use the links below to jump to a specific section:
.. contents::
:local:
:depth: 1
Before you get started, you're going to need a few things:
- Your favorite IDE or text editor
- Python 3.6 or later
- PIP
- Streamlit — This one's kind of important, so don't forget to install.
If you haven't already, take a few minutes to read through Main concepts to understand Streamlit's data flow model.
Regardless of which package management tool you're using, we recommend running these commands in a virtual environment. This ensures that the dependencies pulled in for Streamlit don't impact any other Python projects you're working on.
$ pip install streamlit
Now run the hello world app just to make sure everything it's working:
$ streamlit hello
Now that everything's installed, let's create a new Python script and import Streamlit.
-
Create a new Python file named
first_app.py
, then open it with your IDE or text editor. -
Next, import Streamlit.
import streamlit as st # To make things easier later, we're also importing numpy and pandas for # working with sample data. import numpy as np import pandas as pd
-
Run your app. A new tab will open in your default browser. It'll be blank for now. That's OK.
$ streamlit run first_app.py
Running a Streamlit app is no different than any other Python script. Whenever you need to view the app, you can use this command.
.. tip:: Did you know you can also pass a URL to `streamlit run`? This is great when combined with Github Gists. For example: `$ streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/app.py`
-
You can kill the app at any time by typing Ctrl+c in the terminal.
Streamlit has a number of ways to add text to your app. Check out our API reference for a complete list.
Let's add a title to test things out:
st.title('My first app')
That's it! Your app has a title. You can use specific text functions to add
content to your app, or you can use st.write()
and add your own markdown.
Along with magic commands,
st.write()
is Streamlit's "Swiss Army knife". You
can pass almost anything to st.write()
:
text, data, Matplotlib figures, Altair charts, and more. Don't worry, Streamlit
will figure it out and render things the right way.
st.write("Here's our first attempt at using data to create a table:")
st.write(pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
}))
There are other data specific functions like
st.dataframe()
and
st.table()
that you can also use for displaying
data. Check our advanced guides on displaying data to understand when to use
these features and how to add colors and styling to your data frames.
.. tip::
For this guide we're using small amounts of data so that we can move
quickly. You can check out our `Tutorial on creating a data explorer
<tutorial/create_a_data_explorer_app.html>`_ to see an example of how to
load data from an API and use `@st.cache <api.html#streamlit.cache>`_ to
cache it.
If you're using Python 3, you can also write to your app without calling any
Streamlit methods. Streamlit supports "magic
commands," which means you don't have to use
st.write()
at all! Try replacing the code above
with this snippet:
"""
# My first app
Here's our first attempt at using data to create a table:
"""
df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
df
How it works is simple. Any time that Streamlit sees a variable or a literal
value on its own line, it automatically writes that to your app using
st.write()
. For more information, refer to the
documentation on magic commands.
Streamlit supports several popular data charting libraries like Matplotlib, Altair, Deck.Gl, and more. In this section, you'll add a bar chart, line chart, and a map to your app.
You can easily add a line chart to your app with
st.line_chart()
. We'll generate a random
sample using Numpy and then chart it.
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
With st.map()
you can display data points on a map.
Let's use Numpy to generate some sample data and plot it on a map of
San Francisco.
map_data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])
st.map(map_data)
With widgets, Streamlit allows you to bake interactivity directly into your apps with checkboxes, buttons, sliders, and more. Check out our API reference for a full list of interactive widgets.
One use case for checkboxes is to hide or show a specific chart or section in
an app. st.checkbox()
takes a single argument,
which is the widget label. In this sample, the checkbox is used to toggle a
conditional statement.
if st.checkbox('Show dataframe'):
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
Use st.selectbox
to choose from a series. You
can write in the options you want, or pass through an array or data frame
column.
Let's use the df
data frame we created earlier.
option = st.selectbox(
'Which number do you like best?',
df['first column'])
'You selected: ', option
For a cleaner look, you can move your widgets into a sidebar. This keeps your
app central, while widgets are pinned to the left. Let's take a look at how you
can use st.sidebar
in your app.
option = st.sidebar.selectbox(
'Which number do you like best?',
df['first column'])
'You selected:', option
Most of the elements you can put into your app can also be put into a sidebar using this syntax:
st.sidebar.[element_name]()
. Here are a few examples that show how it's used: st.sidebar.markdown()
, st.sidebar.slider()
, st.sidebar.line_chart()
.
The only exceptions right now are st.write
(you
should use st.sidebar.markdown()
instead), st.echo
, and st.spinner
. Rest
assured, though, we're currently working on adding support for those too!
When adding long running computations to an app, you can use
st.progress()
to display status in real time.
First, let's import time. We're going to use the time.sleep()
method to
simulate a long running computation:
import time
Now, let's create a progress bar:
'Starting a long computation...'
# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)
for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Iteration {i+1}')
bar.progress(i + 1)
time.sleep(0.1)
'...and now we\'re done!'
After you've built a Streamlit app, you may want to discuss some of it with co-workers over email or Slack, or share it with the world on Twitter. A great way to do that is with Streamlit's built-in screencast recorder. With it, you can record, narrate, stop, save, and share with a few clicks.
To start a screencast, locate the menu in the upper right corner of your app (☰), select Record a screencast, and follow the prompts. Before the recording starts, you'll see a countdown — this means it's showtime.
To stop your screencast, go back to the menu (☰) and select Stop recording (or hit the ESC key). Follow the prompts to preview your recording and save it to disk. That's it, you're ready to share your Streamlit app.
.. image:: ./media/screenshare.gif
That's it for getting started, now you can go and build your own apps! If you run into difficulties here are a few things you can do.
- Check out our community forum and post a question
- Quick help from command line with
$ streamlit --help
- Read more documentation! Check out:
- Tutorials to make an app
- Advanced concepts for things like caching and inserting elements out of order
- API reference for examples of every Streamlit command