API reference

Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples.

Know what you’re looking for? Use these links or the left nav to move through this API reference.

Magic commands

Magic commands are a feature in Streamlit that allows you to write markdown and data to your app with very few keypresses. Here’s an example:

# Draw a title and some text to the app:
'''
# This is the document title

This is some _markdown_.
'''

df = pd.DataFrame({'col1': [1,2,3]})
df  # <-- Draw the dataframe

x = 10
'x', x  # <-- Draw the string 'x' and then the value of x

Any time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write (which you’ll learn about later).

Also, magic is smart enough to ignore docstrings. That is, it ignores the strings at the top of files and functions.

If you prefer to call Streamlit commands more explicitly, you can always turn magic off in your ~/.streamlit/config.toml with the following setting:

[runner]
magicEnabled = false

Important

Right now, Magic only works in the main Python app file, not in imported files. See GitHub issue #288 for a discussion of the issues.

Display text

Streamlit apps usually start with a call to st.title to set the app’s title. After that, there are 2 heading levels you can use: st.header and st.subheader.

Pure text is entered with st.text, and Markdown with st.markdown.

We also offer a “swiss-army knife” command called st.write, which accepts multiple arguments, and multiple data types. And as described above, you can also use magic commands in place of st.write.

streamlit.text(body)

Write fixed-width and preformatted text.

Parameters

body (str) – The string to display.

Example

>>> st.text('This is some text.')
(view standalone Streamlit app)
streamlit.markdown(body, unsafe_allow_html=False)

Display string formatted as Markdown.

Parameters
  • body (str) –

    The string to display as Github-flavored Markdown. Syntax information can be found at: https://github.github.com/gfm.

    This also supports:

  • unsafe_allow_html (bool) –

    By default, any HTML tags found in the body will be escaped and therefore treated as pure text. This behavior may be turned off by setting this argument to True.

    That said, we strongly advise against it. It is hard to write secure HTML, so by using this argument you may be compromising your users’ security. For more information, see:

    https://github.com/streamlit/streamlit/issues/152

    Also note that `unsafe_allow_html` is a temporary measure and may be removed from Streamlit at any time.

    If you decide to turn on HTML anyway, we ask you to please tell us your exact use case here:

    https://discuss.streamlit.io/t/96

    This will help us come up with safe APIs that allow you to do what you want.

Example

>>> st.markdown('Streamlit is **_really_ cool**.')
(view standalone Streamlit app)
streamlit.latex(body)

Display mathematical expressions formatted as LaTeX.

Supported LaTeX functions are listed at https://katex.org/docs/supported.html.

Parameters

body (str or SymPy expression) – The string or SymPy expression to display as LaTeX. If str, it’s a good idea to use raw Python strings since LaTeX uses backslashes a lot.

Example

>>> st.latex(r'''
...     a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
...     \sum_{k=0}^{n-1} ar^k =
...     a \left(\frac{1-r^{n}}{1-r}\right)
...     ''')
(view standalone Streamlit app)
streamlit.write(*args, **kwargs)

Write arguments to the app.

This is the Swiss Army knife of Streamlit commands: it does different things depending on what you throw at it. Unlike other Streamlit commands, write() has some unique properties:

  1. You can pass in multiple arguments, all of which will be written.

  2. Its behavior depends on the input types as follows.

  3. It returns None, so it’s “slot” in the App cannot be reused.

Parameters
  • *args (any) –

    One or many objects to print to the App.

    Arguments are handled as follows:

    • write(string)Prints the formatted Markdown string, with

      support for LaTeX expression and emoji shortcodes. See docs for st.markdown for more.

    • write(data_frame) : Displays the DataFrame as a table.

    • write(error) : Prints an exception specially.

    • write(func) : Displays information about a function.

    • write(module) : Displays information about the module.

    • write(dict) : Displays dict in an interactive widget.

    • write(obj) : The default is to print str(obj).

    • write(mpl_fig) : Displays a Matplotlib figure.

    • write(altair) : Displays an Altair chart.

    • write(keras) : Displays a Keras model.

    • write(graphviz) : Displays a Graphviz graph.

    • write(plotly_fig) : Displays a Plotly figure.

    • write(bokeh_fig) : Displays a Bokeh figure.

    • write(sympy_expr) : Prints SymPy expression using LaTeX.

  • unsafe_allow_html (bool) –

    This is a keyword-only argument that defaults to False.

    By default, any HTML tags found in strings will be escaped and therefore treated as pure text. This behavior may be turned off by setting this argument to True.

    That said, we strongly advise against it*. It is hard to write secure HTML, so by using this argument you may be compromising your users’ security. For more information, see:

    https://github.com/streamlit/streamlit/issues/152

    Also note that `unsafe_allow_html` is a temporary measure and may be removed from Streamlit at any time.

    If you decide to turn on HTML anyway, we ask you to please tell us your exact use case here: https://discuss.streamlit.io/t/96 .

    This will help us come up with safe APIs that allow you to do what you want.

Example

Its basic use case is to draw Markdown-formatted text, whenever the input is a string:

>>> write('Hello, *World!* :sunglasses:')
(view standalone Streamlit app)

As mentioned earlier, st.write() also accepts other data formats, such as numbers, data frames, styled data frames, and assorted objects:

>>> st.write(1234)
>>> st.write(pd.DataFrame({
...     'first column': [1, 2, 3, 4],
...     'second column': [10, 20, 30, 40],
... }))
(view standalone Streamlit app)

Finally, you can pass in multiple arguments to do things like:

>>> st.write('1 + 1 = ', 2)
>>> st.write('Below is a DataFrame:', data_frame, 'Above is a dataframe.')
(view standalone Streamlit app)

Oh, one more thing: st.write accepts chart objects too! For example:

>>> import pandas as pd
>>> import numpy as np
>>> import altair as alt
>>>
>>> df = pd.DataFrame(
...     np.random.randn(200, 3),
...     columns=['a', 'b', 'c'])
...
>>> c = alt.Chart(df).mark_circle().encode(
...     x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
>>>
>>> st.write(c)
(view standalone Streamlit app)
streamlit.title(body)

Display text in title formatting.

Each document should have a single st.title(), although this is not enforced.

Parameters

body (str) – The text to display.

Example

>>> st.title('This is a title')
(view standalone Streamlit app)
streamlit.header(body)

Display text in header formatting.

Parameters

body (str) – The text to display.

Example

>>> st.header('This is a header')
(view standalone Streamlit app)
streamlit.subheader(body)

Display text in subheader formatting.

Parameters

body (str) – The text to display.

Example

>>> st.subheader('This is a subheader')
(view standalone Streamlit app)
streamlit.code(body, language='python')

Display a code block with optional syntax highlighting.

(This is a convenience wrapper around st.markdown())

Parameters
  • body (str) – The string to display as code.

  • language (str) – The language that the code is written in, for syntax highlighting. If omitted, the code will be unstyled.

Example

>>> code = '''def hello():
...     print("Hello, Streamlit!")'''
>>> st.code(code, language='python')
(view standalone Streamlit app)

Display data

When you’re working with data, it is extremely valuable to visualize that data quickly, interactively, and from multiple different angles. That’s what Streamlit is actually built and optimized for.

You can display data via charts, and you can display it in raw form. These are the Streamlit commands you can use to display raw data.

streamlit.dataframe(data=None, width=None, height=None)

Display a dataframe as an interactive table.

Parameters
  • data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,) –

    or None The data to display.

    If ‘data’ is a pandas.Styler, it will be used to style its underyling DataFrame. Streamlit supports custom cell values and colors. (It does not support some of the more exotic pandas styling features, like bar charts, hovering, and captions.) Styler support is experimental!

  • width (int or None) – Desired width of the UI element expressed in pixels. If None, a default width based on the page width is used.

  • height (int or None) – Desired height of the UI element expressed in pixels. If None, a default height is used.

Examples

>>> df = pd.DataFrame(
...    np.random.randn(50, 20),
...    columns=('col %d' % i for i in range(20)))
...
>>> st.dataframe(df)  # Same as st.write(df)
(view standalone Streamlit app)
>>> st.dataframe(df, 200, 100)

You can also pass a Pandas Styler object to change the style of the rendered DataFrame:

>>> df = pd.DataFrame(
...    np.random.randn(10, 20),
...    columns=('col %d' % i for i in range(20)))
...
>>> st.dataframe(df.style.highlight_max(axis=0))
(view standalone Streamlit app)
streamlit.table(data=None)

Display a static table.

This differs from st.dataframe in that the table in this case is static: its entire contents are laid out directly on the page.

Parameters

data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,) – or None The table data.

Example

>>> df = pd.DataFrame(
...    np.random.randn(10, 5),
...    columns=('col %d' % i for i in range(5)))
...
>>> st.table(df)
(view standalone Streamlit app)
streamlit.json(body)

Display object or string as a pretty-printed JSON string.

Parameters

body (Object or str) – The object to print as JSON. All referenced objects should be serializable to JSON as well. If object is a string, we assume it contains serialized JSON.

Example

>>> st.json({
...     'foo': 'bar',
...     'baz': 'boz',
...     'stuff': [
...         'stuff 1',
...         'stuff 2',
...         'stuff 3',
...         'stuff 5',
...     ],
... })
(view standalone Streamlit app)

Display charts

Streamlit supports several different charting libraries, and our goal is to continually add support for more. Right now, the most basic library in our arsenal is Matplotlib. Then there are also interactive charting libraries like Vega Lite (2D charts) and deck.gl (maps and 3D charts). And finally we also provide a few chart types that are “native” to Streamlit, like st.line_chart and st.area_chart.

streamlit.line_chart(data=None, width=0, height=0, use_container_width=True)

Display a line chart.

This is syntax-sugar around st.altair_chart. The main difference is this command uses the data’s own column and indices to figure out the chart’s spec. As a result this is easier to use for many “just plot this” scenarios, while being less customizable.

Parameters
  • data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict) – or None Data to be plotted.

  • width (int) – The chart width in pixels. If 0, selects the width automatically.

  • height (int) – The chart width in pixels. If 0, selects the height automatically.

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over the width argument.

Example

>>> chart_data = pd.DataFrame(
...     np.random.randn(20, 3),
...     columns=['a', 'b', 'c'])
...
>>> st.line_chart(chart_data)
(view standalone Streamlit app)
streamlit.area_chart(data=None, width=0, height=0, use_container_width=True)

Display a area chart.

This is just syntax-sugar around st.altair_chart. The main difference is this command uses the data’s own column and indices to figure out the chart’s spec. As a result this is easier to use for many “just plot this” scenarios, while being less customizable.

Parameters
  • data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, or dict) – Data to be plotted.

  • width (int) – The chart width in pixels. If 0, selects the width automatically.

  • height (int) – The chart width in pixels. If 0, selects the height automatically.

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over the width argument.

Example

>>> chart_data = pd.DataFrame(
...     np.random.randn(20, 3),
...     columns=['a', 'b', 'c'])
...
>>> st.area_chart(chart_data)
(view standalone Streamlit app)
streamlit.bar_chart(data=None, width=0, height=0, use_container_width=True)

Display a bar chart.

This is just syntax-sugar around st.altair_chart. The main difference is this command uses the data’s own column and indices to figure out the chart’s spec. As a result this is easier to use for many “just plot this” scenarios, while being less customizable.

Parameters
  • data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, or dict) – Data to be plotted.

  • width (int) – The chart width in pixels. If 0, selects the width automatically.

  • height (int) – The chart width in pixels. If 0, selects the height automatically.

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over the width argument.

Example

>>> chart_data = pd.DataFrame(
...     np.random.randn(50, 3),
...     columns=["a", "b", "c"])
...
>>> st.bar_chart(chart_data)
(view standalone Streamlit app)
streamlit.pyplot(fig=None, clear_figure=None, **kwargs)

Display a matplotlib.pyplot figure.

Parameters
  • fig (Matplotlib Figure) – The figure to plot. When this argument isn’t specified, this function will render the global figure (but this is deprecated, as described below)

  • clear_figure (bool) –

    If True, the figure will be cleared after being rendered. If False, the figure will not be cleared after being rendered. If left unspecified, we pick a default based on the value of fig.

    • If fig is set, defaults to False.

    • If fig is not set, defaults to True. This simulates Jupyter’s approach to matplotlib rendering.

  • **kwargs (any) – Arguments to pass to Matplotlib’s savefig function.

Example

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>>
>>> arr = np.random.normal(1, 1, size=100)
>>> fig, ax = plt.subplots()
>>> ax.hist(arr, bins=20)
>>>
>>> st.pyplot(fig)
(view standalone Streamlit app)

Notes

Note

Deprecation warning. After December 1st, 2020, we will remove the ability to specify no arguments in st.pyplot(), as that requires the use of Matplotlib’s global figure object, which is not thread-safe. So please always pass a figure object as shown in the example section above.

Matplotlib support several different types of “backends”. If you’re getting an error using Matplotlib with Streamlit, try setting your backend to “TkAgg”:

echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc

For more information, see https://matplotlib.org/faq/usage_faq.html.

streamlit.altair_chart(altair_chart, use_container_width=False)

Display a chart using the Altair library.

Parameters
  • altair_chart (altair.vegalite.v2.api.Chart) – The Altair chart object to display.

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over Altair’s native width value.

Example

>>> import pandas as pd
>>> import numpy as np
>>> import altair as alt
>>>
>>> df = pd.DataFrame(
...     np.random.randn(200, 3),
...     columns=['a', 'b', 'c'])
...
>>> c = alt.Chart(df).mark_circle().encode(
...     x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
>>>
>>> st.altair_chart(c, use_container_width=True)
(view standalone Streamlit app)

Examples of Altair charts can be found at https://altair-viz.github.io/gallery/.

streamlit.vega_lite_chart(data=None, spec=None, use_container_width=False, **kwargs)

Display a chart using the Vega-Lite library.

Parameters
  • data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,) – or None Either the data to be plotted or a Vega-Lite spec containing the data (which more closely follows the Vega-Lite API).

  • spec (dict or None) – The Vega-Lite spec for the chart. If the spec was already passed in the previous argument, this must be set to None. See https://vega.github.io/vega-lite/docs/ for more info.

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over Vega-Lite’s native width value.

  • **kwargs (any) – Same as spec, but as keywords.

Example

>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(
...     np.random.randn(200, 3),
...     columns=['a', 'b', 'c'])
>>>
>>> st.vega_lite_chart(df, {
...     'mark': {'type': 'circle', 'tooltip': True},
...     'encoding': {
...         'x': {'field': 'a', 'type': 'quantitative'},
...         'y': {'field': 'b', 'type': 'quantitative'},
...         'size': {'field': 'c', 'type': 'quantitative'},
...         'color': {'field': 'c', 'type': 'quantitative'},
...     },
... })
(view standalone Streamlit app)

Examples of Vega-Lite usage without Streamlit can be found at https://vega.github.io/vega-lite/examples/. Most of those can be easily translated to the syntax shown above.

streamlit.plotly_chart(figure_or_data, use_container_width=False, sharing='streamlit', **kwargs)

Display an interactive Plotly chart.

Plotly is a charting library for Python. The arguments to this function closely follow the ones for Plotly’s plot() function. You can find more about Plotly at https://plot.ly/python.

Parameters
  • figure_or_data (plotly.graph_objs.Figure, plotly.graph_objs.Data,) –

    dict/list of plotly.graph_objs.Figure/Data

    See https://plot.ly/python/ for examples of graph descriptions.

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over the figure’s native width value.

  • sharing ({'streamlit', 'private', 'secret', 'public'}) – Use ‘streamlit’ to insert the plot and all its dependencies directly in the Streamlit app, which means it works offline too. This is the default. Use any other sharing mode to send the app to Plotly’s servers, and embed the result into the Streamlit app. See https://plot.ly/python/privacy/ for more. Note that these sharing modes require a Plotly account.

  • **kwargs – Any argument accepted by Plotly’s plot() function.

To show Plotly charts in Streamlit, call st.plotly_chart wherever you would call Plotly’s py.plot or py.iplot.

Example

The example below comes straight from the examples at https://plot.ly/python:

>>> import streamlit as st
>>> import plotly.figure_factory as ff
>>> import numpy as np
>>>
>>> # Add histogram data
>>> x1 = np.random.randn(200) - 2
>>> x2 = np.random.randn(200)
>>> x3 = np.random.randn(200) + 2
>>>
>>> # Group data together
>>> hist_data = [x1, x2, x3]
>>>
>>> group_labels = ['Group 1', 'Group 2', 'Group 3']
>>>
>>> # Create distplot with custom bin_size
>>> fig = ff.create_distplot(
...         hist_data, group_labels, bin_size=[.1, .25, .5])
>>>
>>> # Plot!
>>> st.plotly_chart(fig, use_container_width=True)
(view standalone Streamlit app)
streamlit.bokeh_chart(figure, use_container_width=False)

Display an interactive Bokeh chart.

Bokeh is a charting library for Python. The arguments to this function closely follow the ones for Bokeh’s show function. You can find more about Bokeh at https://bokeh.pydata.org.

Parameters
  • figure (bokeh.plotting.figure.Figure) – A Bokeh figure to plot.

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over Bokeh’s native width value.

  • show Bokeh charts in Streamlit, call st.bokeh_chart (To) –

  • you would call Bokeh's show. (wherever) –

Example

>>> import streamlit as st
>>> from bokeh.plotting import figure
>>>
>>> x = [1, 2, 3, 4, 5]
>>> y = [6, 7, 2, 4, 5]
>>>
>>> p = figure(
...     title='simple line example',
...     x_axis_label='x',
...     y_axis_label='y')
...
>>> p.line(x, y, legend='Trend', line_width=2)
>>>
>>> st.bokeh_chart(p, use_container_width=True)
(view standalone Streamlit app)
streamlit.pydeck_chart(pydeck_obj=None, use_container_width=False)

Draw a chart using the PyDeck library.

This supports 3D maps, point clouds, and more! More info about PyDeck at https://deckgl.readthedocs.io/en/latest/.

These docs are also quite useful:

When using this command, we advise all users to use a personal Mapbox token. This ensures the map tiles used in this chart are more robust. You can do this with the mapbox.token config option.

To get a token for yourself, create an account at https://mapbox.com. It’s free! (for moderate usage levels) See https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options.

Parameters

spec (pydeck.Deck or None) – Object specifying the PyDeck chart to draw.

Example

Here’s a chart using a HexagonLayer and a ScatterplotLayer on top of the light map style:

>>> df = pd.DataFrame(
...    np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
...    columns=['lat', 'lon'])
>>>
>>> st.pydeck_chart(pdk.Deck(
...     map_style='mapbox://styles/mapbox/light-v9',
...     initial_view_state=pdk.ViewState(
...         latitude=37.76,
...         longitude=-122.4,
...         zoom=11,
...         pitch=50,
...     ),
...     layers=[
...         pdk.Layer(
...            'HexagonLayer',
...            data=df,
...            get_position='[lon, lat]',
...            radius=200,
...            elevation_scale=4,
...            elevation_range=[0, 1000],
...            pickable=True,
...            extruded=True,
...         ),
...         pdk.Layer(
...             'ScatterplotLayer',
...             data=df,
...             get_position='[lon, lat]',
...             get_color='[200, 30, 0, 160]',
...             get_radius=200,
...         ),
...     ],
... ))
(view standalone Streamlit app)
streamlit.graphviz_chart(figure_or_dot, use_container_width=False)

Display a graph using the dagre-d3 library.

Parameters
  • figure_or_dot (graphviz.dot.Graph, graphviz.dot.Digraph, str) – The Graphlib graph object or dot string to display

  • use_container_width (bool) – If True, set the chart width to the column width. This takes precedence over the figure’s native width value.

Example

>>> import streamlit as st
>>> import graphviz as graphviz
>>>
>>> # Create a graphlib graph object
>>> graph = graphviz.Digraph()
>>> graph.edge('run', 'intr')
>>> graph.edge('intr', 'runbl')
>>> graph.edge('runbl', 'run')
>>> graph.edge('run', 'kernel')
>>> graph.edge('kernel', 'zombie')
>>> graph.edge('kernel', 'sleep')
>>> graph.edge('kernel', 'runmem')
>>> graph.edge('sleep', 'swap')
>>> graph.edge('swap', 'runswap')
>>> graph.edge('runswap', 'new')
>>> graph.edge('runswap', 'runmem')
>>> graph.edge('new', 'runmem')
>>> graph.edge('sleep', 'runmem')
>>>
>>> st.graphviz_chart(graph)

Or you can render the chart from the graph using GraphViz’s Dot language:

>>> st.graphviz_chart('''
    digraph {
        run -> intr
        intr -> runbl
        runbl -> run
        run -> kernel
        kernel -> zombie
        kernel -> sleep
        kernel -> runmem
        sleep -> swap
        swap -> runswap
        runswap -> new
        runswap -> runmem
        new -> runmem
        sleep -> runmem
    }
''')
(view standalone Streamlit app)
streamlit.map(data=None, zoom=None, use_container_width=True)

Display a map with points on it.

This is a wrapper around st.pydeck_chart to quickly create scatterplot charts on top of a map, with auto-centering and auto-zoom.

When using this command, we advise all users to use a personal Mapbox token. This ensures the map tiles used in this chart are more robust. You can do this with the mapbox.token config option.

To get a token for yourself, create an account at https://mapbox.com. It’s free! (for moderate usage levels) See https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options.

Parameters
  • data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,) – or None The data to be plotted. Must have columns called ‘lat’, ‘lon’, ‘latitude’, or ‘longitude’.

  • zoom (int) – Zoom level as specified in https://wiki.openstreetmap.org/wiki/Zoom_levels

Example

>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(
...     np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
...     columns=['lat', 'lon'])
>>>
>>> st.map(df)
(view standalone Streamlit app)

Display media

It’s easy to embed images, videos, and audio files directly into your Streamlit apps.

streamlit.image(image, caption=None, width=None, use_column_width=False, clamp=False, channels='RGB', output_format='auto', **kwargs)

Display an image or list of images.

Parameters
  • image (numpy.ndarray, [numpy.ndarray], BytesIO, str, or [str]) – Monochrome image of shape (w,h) or (w,h,1) OR a color image of shape (w,h,3) OR an RGBA image of shape (w,h,4) OR a URL to fetch the image from OR an SVG XML string like <svg xmlns=…</svg> OR a list of one of the above, to display multiple images.

  • caption (str or list of str) – Image caption. If displaying multiple images, caption should be a list of captions (one for each image).

  • width (int or None) – Image width. None means use the image width. Should be set for SVG images, as they have no default image width.

  • use_column_width (bool) – If True, set the image width to the column width. This takes precedence over the width parameter.

  • clamp (bool) – Clamp image pixel values to a valid range ([0-255] per channel). This is only meaningful for byte array images; the parameter is ignored for image URLs. If this is not set, and an image has an out-of-range value, an error will be thrown.

  • channels ('RGB' or 'BGR') – If image is an nd.array, this parameter denotes the format used to represent color information. Defaults to ‘RGB’, meaning image[:, :, 0] is the red channel, image[:, :, 1] is green, and image[:, :, 2] is blue. For images coming from libraries like OpenCV you should set this to ‘BGR’, instead.

  • output_format ('JPEG', 'PNG', or 'auto') – This parameter specifies the format to use when transferring the image data. Photos should use the JPEG format for lossy compression while diagrams should use the PNG format for lossless compression. Defaults to ‘auto’ which identifies the compression type based on the type and format of the image argument.

Example

>>> from PIL import Image
>>> image = Image.open('sunrise.jpg')
>>>
>>> st.image(image, caption='Sunrise by the mountains',
...          use_column_width=True)
(view standalone Streamlit app)
streamlit.audio(data, format='audio/wav', start_time=0)

Display an audio player.

Parameters
  • data (str, bytes, BytesIO, numpy.ndarray, or file opened with) – io.open(). Raw audio data, filename, or a URL pointing to the file to load. Numpy arrays and raw data formats must include all necessary file headers to match specified file format.

  • start_time (int) – The time from which this element should start playing.

  • format (str) – The mime type for the audio file. Defaults to ‘audio/wav’. See https://tools.ietf.org/html/rfc4281 for more info.

Example

>>> audio_file = open('myaudio.ogg', 'rb')
>>> audio_bytes = audio_file.read()
>>>
>>> st.audio(audio_bytes, format='audio/ogg')
(view standalone Streamlit app)
streamlit.video(data, format='video/mp4', start_time=0)

Display a video player.

Parameters
  • data (str, bytes, BytesIO, numpy.ndarray, or file opened with) – io.open(). Raw video data, filename, or URL pointing to a video to load. Includes support for YouTube URLs. Numpy arrays and raw data formats must include all necessary file headers to match specified file format.

  • format (str) – The mime type for the video file. Defaults to ‘video/mp4’. See https://tools.ietf.org/html/rfc4281 for more info.

  • start_time (int) – The time from which this element should start playing.

Example

>>> video_file = open('myvideo.mp4', 'rb')
>>> video_bytes = video_file.read()
>>>
>>> st.video(video_bytes)
(view standalone Streamlit app)

Note

Some videos may not display if they are encoded using MP4V (which is an export option in OpenCV), as this codec is not widely supported by browsers. Converting your video to H.264 will allow the video to be displayed in Streamlit. See this StackOverflow post or this Streamlit forum post for more information.

Display interactive widgets

With widgets, Streamlit allows you to bake interactivity directly into your apps with buttons, sliders, text inputs, and more.

streamlit.button(label, key=None)

Display a button widget.

Parameters
  • label (str) – A short label explaining to the user what this button is for.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

If the button was clicked on the last run of the app.

Return type

bool

Example

>>> if st.button('Say hello'):
...     st.write('Why hello there')
... else:
...     st.write('Goodbye')
streamlit.checkbox(label, value=False, key=None)

Display a checkbox widget.

Parameters
  • label (str) – A short label explaining to the user what this checkbox is for.

  • value (bool) – Preselect the checkbox when it first renders. This will be cast to bool internally.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

Whether or not the checkbox is checked.

Return type

bool

Example

>>> agree = st.checkbox('I agree')
>>>
>>> if agree:
...     st.write('Great!')
streamlit.radio(label, options, index=0, format_func=<class 'str'>, key=None)

Display a radio button widget.

Parameters
  • label (str) – A short label explaining to the user what this radio group is for.

  • options (list, tuple, numpy.ndarray, pandas.Series, or pandas.DataFrame) – Labels for the radio options. This will be cast to str internally by default. For pandas.DataFrame, the first column is selected.

  • index (int) – The index of the preselected option on first render.

  • format_func (function) – Function to modify the display of radio options. It receives the raw option as an argument and should output the label to be shown for that option. This has no impact on the return value of the radio.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The selected option.

Return type

any

Example

>>> genre = st.radio(
...     "What's your favorite movie genre",
...     ('Comedy', 'Drama', 'Documentary'))
>>>
>>> if genre == 'Comedy':
...     st.write('You selected comedy.')
... else:
...     st.write("You didn't select comedy.")
streamlit.selectbox(label, options, index=0, format_func=<class 'str'>, key=None)

Display a select widget.

Parameters
  • label (str) – A short label explaining to the user what this select widget is for.

  • options (list, tuple, numpy.ndarray, pandas.Series, or pandas.DataFrame) – Labels for the select options. This will be cast to str internally by default. For pandas.DataFrame, the first column is selected.

  • index (int) – The index of the preselected option on first render.

  • format_func (function) – Function to modify the display of the labels. It receives the option as an argument and its output will be cast to str.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The selected option

Return type

any

Example

>>> option = st.selectbox(
...     'How would you like to be contacted?',
...     ('Email', 'Home phone', 'Mobile phone'))
>>>
>>> st.write('You selected:', option)
streamlit.multiselect(label, options, default=None, format_func=<class 'str'>, key=None)

Display a multiselect widget. The multiselect widget starts as empty.

Parameters
  • label (str) – A short label explaining to the user what this select widget is for.

  • options (list, tuple, numpy.ndarray, pandas.Series, or pandas.DataFrame) – Labels for the select options. This will be cast to str internally by default. For pandas.DataFrame, the first column is selected.

  • default ([str] or None) – List of default values.

  • format_func (function) – Function to modify the display of selectbox options. It receives the raw option as an argument and should output the label to be shown for that option. This has no impact on the return value of the selectbox.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

A list with the selected options

Return type

[str]

Example

>>> options = st.multiselect(
...     'What are your favorite colors',
...     ['Green', 'Yellow', 'Red', 'Blue'],
...     ['Yellow', 'Red'])
>>>
>>> st.write('You selected:', options)

Note

User experience can be degraded for large lists of options (100+), as this widget is not designed to handle arbitrary text search efficiently. See this thread on the Streamlit community forum for more information and GitHub issue #1059 for updates on the issue.

streamlit.slider(label, min_value=None, max_value=None, value=None, step=None, format=None, key=None)

Display a slider widget.

This supports int, float, date, time, and datetime types.

This also allows you to render a range slider by passing a two-element tuple or list as the value.

The difference between st.slider and st.select_slider is that slider only accepts numerical or date/time data and takes a range as input, while select_slider accepts any datatype and takes an iterable set of options.

Parameters
  • label (str or None) – A short label explaining to the user what this slider is for.

  • min_value (a supported type or None) – The minimum permitted value. Defaults to 0 if the value is an int, 0.0 if a float, value - timedelta(days=14) if a date/datetime, time.min if a time

  • max_value (a supported type or None) – The maximum permitted value. Defaults to 100 if the value is an int, 1.0 if a float, value + timedelta(days=14) if a date/datetime, time.max if a time

  • value (a supported type or a tuple/list of supported types or None) – The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to min_value.

  • step (int/float/timedelta or None) – The stepping interval. Defaults to 1 if the value is an int, 0.01 if a float, timedelta(days=1) if a date/datetime, timedelta(minutes=15) if a time (or if max_value - min_value < 1 day)

  • format (str or None) – A printf-style format string controlling how the interface should display numbers. This does not impact the return value. Formatter for int/float supports: %d %e %f %g %i Formatter for date/time/datetime uses Moment.js notation: https://momentjs.com/docs/#/displaying/format/

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The current value of the slider widget. The return type will match the data type of the value parameter.

Return type

int/float/date/time/datetime or tuple of int/float/date/time/datetime

Examples

>>> age = st.slider('How old are you?', 0, 130, 25)
>>> st.write("I'm ", age, 'years old')

And here’s an example of a range slider:

>>> values = st.slider(
...     'Select a range of values',
...     0.0, 100.0, (25.0, 75.0))
>>> st.write('Values:', values)

This is a range time slider:

>>> from datetime import time
>>> appointment = st.slider(
...     "Schedule your appointment:",
...     value=(time(11, 30), time(12, 45)))
>>> st.write("You're scheduled for:", appointment)

Finally, a datetime slider:

>>> from datetime import datetime
>>> start_time = st.slider(
...     "When do you start?",
...     value=datetime(2020, 1, 1, 9, 30),
...     format="MM/DD/YY - hh:mm")
>>> st.write("Start time:", start_time)
streamlit.select_slider(label, options=[], value=None, format_func=<class 'str'>, key=None)

Display a slider widget to select items from a list.

This also allows you to render a range slider by passing a two-element tuple or list as the value.

The difference between st.select_slider and st.slider is that select_slider accepts any datatype and takes an iterable set of options, while slider only accepts numerical or date/time data and takes a range as input.

Parameters
  • label (str or None) – A short label explaining to the user what this slider is for.

  • options (list, tuple, numpy.ndarray, pandas.Series, or pandas.DataFrame) – Labels for the slider options. All options will be cast to str internally by default. For pandas.DataFrame, the first column is selected.

  • value (a supported type or a tuple/list of supported types or None) – The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to first option.

  • format_func (function) – Function to modify the display of the labels from the options. argument. It receives the option as an argument and its output will be cast to str.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The current value of the slider widget. The return type will match the data type of the value parameter.

Return type

any value or tuple of any value

Examples

>>> color = st.select_slider(
...     'Select a color of the rainbow',
...     options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])
>>> st.write('My favorite color is', color)

And here’s an example of a range select slider:

>>> start_color, end_color = st.select_slider(
...     'Select a range of color wavelength',
...     options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
...     value=('red', 'blue'))
>>> st.write('You selected wavelengths between', start_color, 'and', end_color)
streamlit.text_input(label, value='', max_chars=None, key=None, type='default')

Display a single-line text input widget.

Parameters
  • label (str) – A short label explaining to the user what this input is for.

  • value (any) – The text value of this widget when it first renders. This will be cast to str internally.

  • max_chars (int or None) – Max number of characters allowed in text input.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

  • type (str) – The type of the text input. This can be either “default” (for a regular text input), or “password” (for a text input that masks the user’s typed value). Defaults to “default”.

Returns

The current value of the text input widget.

Return type

str

Example

>>> title = st.text_input('Movie title', 'Life of Brian')
>>> st.write('The current movie title is', title)
streamlit.number_input(label, min_value=None, max_value=None, value=<streamlit.elements.utils.NoValue object>, step=None, format=None, key=None)

Display a numeric input widget.

Parameters
  • label (str or None) – A short label explaining to the user what this input is for.

  • min_value (int or float or None) – The minimum permitted value. If None, there will be no minimum.

  • max_value (int or float or None) – The maximum permitted value. If None, there will be no maximum.

  • value (int or float or None) – The value of this widget when it first renders. Defaults to min_value, or 0.0 if min_value is None

  • step (int or float or None) – The stepping interval. Defaults to 1 if the value is an int, 0.01 otherwise. If the value is not specified, the format parameter will be used.

  • format (str or None) – A printf-style format string controlling how the interface should display numbers. Output must be purely numeric. This does not impact the return value. Valid formatters: %d %e %f %g %i

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The current value of the numeric input widget. The return type will match the data type of the value parameter.

Return type

int or float

Example

>>> number = st.number_input('Insert a number')
>>> st.write('The current number is ', number)
streamlit.text_area(label, value='', height=None, max_chars=None, key=None)

Display a multi-line text input widget.

Parameters
  • label (str) – A short label explaining to the user what this input is for.

  • value (any) – The text value of this widget when it first renders. This will be cast to str internally.

  • height (int or None) – Desired height of the UI element expressed in pixels. If None, a default height is used.

  • max_chars (int or None) – Maximum number of characters allowed in text area.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The current value of the text input widget.

Return type

str

Example

>>> txt = st.text_area('Text to analyze', '''
...     It was the best of times, it was the worst of times, it was
...     the age of wisdom, it was the age of foolishness, it was
...     the epoch of belief, it was the epoch of incredulity, it
...     was the season of Light, it was the season of Darkness, it
...     was the spring of hope, it was the winter of despair, (...)
...     ''')
>>> st.write('Sentiment:', run_sentiment_analysis(txt))
streamlit.date_input(label, value=None, min_value=None, max_value=None, key=None)

Display a date input widget.

Parameters
  • label (str) – A short label explaining to the user what this date input is for.

  • value (datetime.date or datetime.datetime or list/tuple of datetime.date or datetime.datetime or None) – The value of this widget when it first renders. If a list/tuple with 0 to 2 date/datetime values is provided, the datepicker will allow users to provide a range. Defaults to today as a single-date picker.

  • min_value (datetime.date or datetime.datetime) – The minimum selectable date. Defaults to today-10y.

  • max_value (datetime.date or datetime.datetime) – The maximum selectable date. Defaults to today+10y.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The current value of the date input widget.

Return type

datetime.date

Example

>>> d = st.date_input(
...     "When's your birthday",
...     datetime.date(2019, 7, 6))
>>> st.write('Your birthday is:', d)
streamlit.time_input(label, value=None, key=None)

Display a time input widget.

Parameters
  • label (str) – A short label explaining to the user what this time input is for.

  • value (datetime.time/datetime.datetime) – The value of this widget when it first renders. This will be cast to str internally. Defaults to the current time.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The current value of the time input widget.

Return type

datetime.time

Example

>>> t = st.time_input('Set an alarm for', datetime.time(8, 45))
>>> st.write('Alarm is set for', t)
streamlit.file_uploader(label, type=None, accept_multiple_files=False, key=None, **kwargs)

Display a file uploader widget. By default, uploaded files are limited to 200MB. You can configure this using the server.maxUploadSize config option.

Parameters
  • label (str or None) – A short label explaining to the user what this file uploader is for.

  • type (str or list of str or None) – Array of allowed extensions. [‘png’, ‘jpg’] The default is None, which means all extensions are allowed.

  • accept_multiple_files (bool) – If True, allows the user to upload multiple files at the same time, in which case the return value will be a list of files. Default: False

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

  • If allow_multiple_files is False, returns either None or an UploadedFile object.

  • If allow_multiple_files is True, returns a list with the uploaded files as UploadedFile objects. If no files were uploaded, returns an empty list.

The UploadedFile class is a subclass of BytesIO, and therefore it is “file-like”. This means you can pass them anywhere where a file is expected.

Return type

None or UploadedFile or list of UploadedFile

Examples

Insert a file uploader that accepts a single file at a time:

>>> uploaded_file = st.file_uploader("Choose a file")
>>> if uploaded_file is not None:
...     # To read file as bytes:
...     bytes_data = uploaded_file.read()
...     st.write(bytes_data)

… # To convert to a string based IO: … stringio = StringIO(uploaded_file.decode(“utf-8”)) … st.write(stringio)

… # To read file as string: … string_data = stringio.read() … st.write(string_data)

… # Can be used wherever a “file-like” object is accepted: … dataframe = pd.read_csv(uploaded_file) … st.write(dataframe)

Insert a file uploader that accepts multiple files at a time:

>>> uploaded_files = st.file_uploader("Choose a CSV file", accept_multiple_files=True)
>>> for uploaded_file in uploaded_files:
...     bytes_data = uploaded_file.read()
...     st.write("filename:", uploaded_file.name)
...     st.write(bytes_data)
streamlit.beta_color_picker(label, value=None, key=None)

Display a color picker widget.

Note: This is a beta feature. See https://docs.streamlit.io/en/latest/api.html#pre-release-features for more information.

Parameters
  • label (str) – A short label explaining to the user what this input is for.

  • value (str or None) – The hex value of this widget when it first renders. If None, defaults to black.

  • key (str) – An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

Returns

The selected color as a hex string.

Return type

str

Example

>>> color = st.beta_color_picker('Pick A Color', '#00f900')
>>> st.write('The current color is', color)

Control flow

By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications.

streamlit.stop()

Stops execution immediately.

Streamlit will not run any statements after st.stop(). We recommend rendering a message to explain why the script has stopped. When run outside of Streamlit, this will raise an Exception.

Example

>>> name = st.text_input('Name')
>>> if not name:
>>>   st.warning('Please input a name.')
>>>   st.stop()
>>> st.success('Thank you for inputting a name.')

Add widgets to sidebar

Not only can you add interactivity to your report with widgets, you can organize them into a sidebar with st.sidebar.[element_name]. Each element that’s passed to st.sidebar is pinned to the left, allowing users to focus on the content in your app. The only elements that aren’t supported are st.echo and st.spinner.

Here’s an example of how you’d add a selectbox to your sidebar.

import streamlit as st

add_selectbox = st.sidebar.selectbox(
    "How would you like to be contacted?",
    ("Email", "Home phone", "Mobile phone")
)

Lay out your app

In addition to the sidebar, you have a few other options for controlling how your app is laid out.

Note

These are beta features. See https://docs.streamlit.io/en/latest/api.html#pre-release-features for more information.

streamlit.beta_container()

Insert a multi-element container.

Inserts an invisible container into your app that can be used to hold multiple elements. This allows you to, for example, insert multiple elements into your app out of order.

To add elements to the returned container, you can use “with” notation (preferred) or just call methods directly on the returned object. See examples below.

Examples

Inserting elements using “with” notation:

>>> with st.beta_container():
...    st.write("This is inside the container")
...
...    # You can call any Streamlit command, including custom components:
...    st.bar_chart(np.random.randn(50, 3))
...
>>> st.write("This is outside the container")
(view standalone Streamlit app)

Inserting elements out of order:

>>> container = st.beta_container()
>>> container.write("This is inside the container")
>>> st.write("This is outside the container")
>>>
>>> # Now insert some more in the container
>>> container.write("This is inside too")
(view standalone Streamlit app)
streamlit.beta_columns(spec)

Insert containers laid out as side-by-side columns.

Inserts a number of multi-element containers laid out side-by-side and returns a list of container objects.

To add elements to the returned containers, you can use “with” notation (preferred) or just call methods directly on the returned object. See examples below.

Warning

Currently, you may not put columns inside another column.

Parameters

spec (int or list of numbers) –

If an int

Specifies the number of columns to insert, and all columns have equal width.

If a list of numbers

Creates a column for each number, and each column’s width is proportional to the number provided. Numbers can be ints or floats, but they must be positive.

For example, st.beta_columns([3, 1, 2]) creates 3 columns where the first column is 3 times the width of the second, and the last column is 2 times that width.

Returns

A list of container objects.

Return type

list of containers

Examples

You can use with notation to insert any element into a column:

>>> col1, col2, col3 = st.beta_columns(3)
>>>
>>> with col1:
...    st.header("A cat")
...    st.image("https://static.streamlit.io/examples/cat.jpg", use_column_width=True)
...
>>> with col2:
...    st.header("A dog")
...    st.image("https://static.streamlit.io/examples/dog.jpg", use_column_width=True)
...
>>> with col3:
...    st.header("An owl")
...    st.image("https://static.streamlit.io/examples/owl.jpg", use_column_width=True)
(view standalone Streamlit app)

Or you can just call methods directly in the returned objects:

>>> col1, col2 = st.beta_columns([3, 1])
>>> data = np.random.randn(10, 1)
>>>
>>> col1.subheader("A wide column with a chart")
>>> col1.line_chart(data)
>>>
>>> col2.subheader("A narrow column with the data")
>>> col2.write(data)
(view standalone Streamlit app)
streamlit.beta_expander(label=None, expanded=False)

Insert a multi-element container that can be expanded/collapsed.

Inserts a container into your app that can be used to hold multiple elements and can be expanded or collapsed by the user. When collapsed, all that is visible is the provided label.

To add elements to the returned container, you can use “with” notation (preferred) or just call methods directly on the returned object. See examples below.

Warning

Currently, you may not put expanders inside another expander.

Parameters
  • label (str) – A string to use as the header for the expander.

  • expanded (bool) – If True, initializes the expander in “expanded” state. Defaults to False (collapsed).

Examples

>>> st.line_chart({"data": [1, 5, 2, 6, 2, 1]})
>>>
>>> with st.beta_expander("See explanation"):
...     st.write("""
...         The chart above shows some numbers I picked for you.
...         I rolled actual dice for these, so they're *guaranteed* to
...         be random.
...     """).
...     st.image("https://static.streamlit.io/examples/dice.jpg")
(view standalone Streamlit app)

Display code

Sometimes you want your Streamlit app to contain both your usual Streamlit graphic elements and the code that generated those elements. That’s where st.echo() comes in.

streamlit.echo(code_location='above')

Use in a with block to draw some code on the app, then execute it.

Parameters

code_location ("above" or "below") – Whether to show the echoed code before or after the results of the executed code block.

Example

>>> with st.echo():
>>>     st.write('This code will be printed')

Ok so let’s say you have the following file, and you want to make its app a little bit more self-explanatory by making that middle section visible in the Streamlit app:

import streamlit as st

def get_user_name():
    return 'John'

# ------------------------------------------------
# Want people to see this part of the code...

def get_punctuation():
    return '!!!'

greeting = "Hi there, "
user_name = get_user_name()
punctuation = get_punctuation()

st.write(greeting, user_name, punctuation)

# ...up to here
# ------------------------------------------------

foo = 'bar'
st.write('Done!')

The file above creates a Streamlit app containing the words “Hi there, John”, and then “Done!”.

Now let’s use st.echo() to make that middle section of the code visible in the app:

import streamlit as st

def get_user_name():
    return 'John'

with st.echo():
    # Everything inside this block will be both printed to the screen
    # and executed.

    def get_punctuation():
        return '!!!'

    greeting = "Hi there, "
    value = get_user_name()
    punctuation = get_punctuation()

    st.write(greeting, value, punctuation)

# And now we're back to _not_ printing to the screen
foo = 'bar'
st.write('Done!')

It’s that simple!

Note

You can have multiple st.echo() blocks in the same file. Use it as often as you wish!

Display progress and status

Streamlit provides a few methods that allow you to add animation to your apps. These animations include progress bars, status messages (like warnings), and celebratory balloons.

streamlit.progress(value)

Display a progress bar.

Parameters

value (int or float) –

0 <= value <= 100 for int

0.0 <= value <= 1.0 for float

Example

Here is an example of a progress bar increasing over time:

>>> import time
>>>
>>> my_bar = st.progress(0)
>>>
>>> for percent_complete in range(100):
...     time.sleep(0.1)
...     my_bar.progress(percent_complete + 1)
streamlit.spinner(text='In progress...')

Temporarily displays a message while executing a block of code.

Parameters

text (str) – A message to display while executing that block

Example

>>> with st.spinner('Wait for it...'):
>>>     time.sleep(5)
>>> st.success('Done!')
streamlit.balloons()

Draw celebratory balloons.

Example

>>> st.balloons()

…then watch your app and get ready for a celebration!

streamlit.error(body)

Display error message.

Parameters

body (str) – The error text to display.

Example

>>> st.error('This is an error')
streamlit.warning(body)

Display warning message.

Parameters

body (str) – The warning text to display.

Example

>>> st.warning('This is a warning')
streamlit.info(body)

Display an informational message.

Parameters

body (str) – The info text to display.

Example

>>> st.info('This is a purely informational message')
streamlit.success(body)

Display a success message.

Parameters

body (str) – The success text to display.

Example

>>> st.success('This is a success message!')
streamlit.exception(exception)

Display an exception.

Parameters

exception (Exception) – The exception to display.

Example

>>> e = RuntimeError('This is an exception of type RuntimeError')
>>> st.exception(e)

Placeholders, help, and options

There are a handful of methods that allow you to create placeholders in your app, provide help using doc strings, and get and modify configuration options.

streamlit.empty()

Insert a single-element container.

Inserts a container into your app that can be used to hold a single element. This allows you to, for example, remove elements at any point, or replace several elements at once (using a child multi-element container).

To insert/replace/clear an element on the returned container, you can use “with” notation or just call methods directly on the returned object. See examples below.

Examples

Overwriting elements in-place using “with” notation:

>>> import time
>>>
>>> with st.empty():
...     for seconds in range(60):
...         st.write(f"⏳ {seconds} seconds have passed")
...         time.sleep(1)
...     st.write("✔️ 1 minute over!")

Replacing several elements, then clearing them:

>>> placeholder = st.empty()
>>>
>>> # Replace the placeholder with some text:
>>> placeholder.text("Hello")
>>>
>>> # Replace the text with a chart:
>>> placeholder.line_chart({"data": [1, 5, 2, 6]})
>>>
>>> # Replace the chart with several elements:
>>> with placeholder.beta_container():
...     st.write("This is one element")
...     st.write("This is another")
...
>>> # Clear all those elements:
>>> placeholder.empty()
streamlit.help(obj)

Display object’s doc string, nicely formatted.

Displays the doc string for this object.

Parameters

obj (Object) – The object whose docstring should be displayed.

Example

Don’t remember how to initialize a dataframe? Try this:

>>> st.help(pandas.DataFrame)

Want to quickly check what datatype is output by a certain function? Try:

>>> x = my_poorly_documented_function()
>>> st.help(x)
streamlit.get_option(key)

Return the current value of a given Streamlit config option.

Run streamlit config show in the terminal to see all available options.

Parameters

key (str) – The config option key of the form “section.optionName”. To see all available options, run streamlit config show on a terminal.

streamlit.set_option(key, value)

Set config option.

Currently, only the following config options can be set within the script itself:
  • client.caching

  • client.displayEnabled

  • deprecation.*

Calling with any other options will raise StreamlitAPIException.

Run streamlit config show in the terminal to see all available options.

Parameters
  • key (str) – The config option key of the form “section.optionName”. To see all available options, run streamlit config show on a terminal.

  • value – The new value to assign to this config option.

streamlit.beta_set_page_config(page_title=None, page_icon=None, layout='centered', initial_sidebar_state='auto')

Configures the default settings of the page.

Note

This must be the first Streamlit command used in your app, and must only be set once.

This is a beta feature. See https://docs.streamlit.io/en/latest/api.html#pre-release-features for more information.

Parameters
  • page_title (str or None) – The page title, shown in the browser tab. If None, defaults to the filename of the script (“app.py” would show “app • Streamlit”).

  • page_icon (Anything supported by st.image or str or None) – The page favicon. Besides the types supported by st.image (like URLs or numpy arrays), you can pass in an emoji as a string (“🦈”) or a shortcode (“:shark:”). Emoji icons are courtesy of Twemoji and loaded from MaxCDN.

  • layout ("centered" or "wide") – How the page content should be laid out. Defaults to “centered”, which constrains the elements into a centered column of fixed width; “wide” uses the entire screen.

  • initial_sidebar_state ("auto" or "expanded" or "collapsed") – How the sidebar should start out. Defaults to “auto”, which hides the sidebar on mobile-sized devices, and shows it otherwise. “expanded” shows the sidebar initially; “collapsed” hides it.

Example

>>> st.beta_set_page_config(
...     page_title="Ex-stream-ly Cool App",
...     page_icon="🧊",
...     layout="wide",
...     initial_sidebar_state="expanded",
... )

Mutate data

With Streamlit you can modify the data within an existing element (chart, table, dataframe).

DeltaGenerator.add_rows(data=None, **kwargs)

Concatenate a dataframe to the bottom of the current one.

Parameters
  • data (pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,) –

  • None (or) – Table to concat. Optional.

  • **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) – The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter).

Example

>>> df1 = pd.DataFrame(
...    np.random.randn(50, 20),
...    columns=('col %d' % i for i in range(20)))
...
>>> my_table = st.table(df1)
>>>
>>> df2 = pd.DataFrame(
...    np.random.randn(50, 20),
...    columns=('col %d' % i for i in range(20)))
...
>>> my_table.add_rows(df2)
>>> # Now the table shown in the Streamlit app contains the data for
>>> # df1 followed by the data for df2.

You can do the same thing with plots. For example, if you want to add more data to a line chart:

>>> # Assuming df1 and df2 from the example above still exist...
>>> my_chart = st.line_chart(df1)
>>> my_chart.add_rows(df2)
>>> # Now the chart shown in the Streamlit app contains the data for
>>> # df1 followed by the data for df2.

And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name:

>>> my_chart = st.vega_lite_chart({
...     'mark': 'line',
...     'encoding': {'x': 'a', 'y': 'b'},
...     'datasets': {
...       'some_fancy_name': df1,  # <-- named dataset
...      },
...     'data': {'name': 'some_fancy_name'},
... }),
>>> my_chart.add_rows(some_fancy_name=df2)  # <-- name used as keyword

Optimize performance

When you mark a function with Streamlit’s cache annotation, it tells Streamlit that whenever the function is called it should check three things:

  1. The name of the function

  2. The actual code that makes up the body of the function

  3. The input parameters that you called the function with

If this is the first time Streamlit has seen those three items, with those exact values, and in that exact combination, it runs the function and stores the result in a local cache.

Then, next time the function is called, if those three values have not changed Streamlit knows it can skip executing the function altogether. Instead, it just reads the output from the local cache and passes it on to the caller.

The main limitation is that Streamlit’s cache feature doesn’t know about changes that take place outside the body of the annotated function.

For more information about the Streamlit cache, its configuration parameters, and its limitations, see Caching.

streamlit.cache(func=None, persist=False, allow_output_mutation=False, show_spinner=True, suppress_st_warning=False, hash_funcs=None, max_entries=None, ttl=None)

Function decorator to memoize function executions.

Parameters
  • func (callable) – The function to cache. Streamlit hashes the function and dependent code.

  • persist (boolean) – Whether to persist the cache on disk.

  • allow_output_mutation (boolean) –

    Streamlit normally shows a warning when return values are not mutated, as that can have unintended consequences. This is done by hashing the return value internally.

    If you know what you’re doing and would like to override this warning, set this to True.

  • show_spinner (boolean) – Enable the spinner. Default is True to show a spinner when there is a cache miss.

  • suppress_st_warning (boolean) – Suppress warnings about calling Streamlit functions from within the cached function.

  • hash_funcs (dict or None) – Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit’s caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used.

  • max_entries (int or None) – The maximum number of entries to keep in the cache, or None for an unbounded cache. (When a new entry is added to a full cache, the oldest cached entry will be removed.) The default is None.

  • ttl (float or None) – The maximum number of seconds to keep an entry in the cache, or None if cache entries should not expire. The default is None.

Example

>>> @st.cache
... def fetch_and_clean_data(url):
...     # Fetch data from URL here, and then clean it up.
...     return data
...
>>> d1 = fetch_and_clean_data(DATA_URL_1)
>>> # Actually executes the function, since this is the first time it was
>>> # encountered.
>>>
>>> d2 = fetch_and_clean_data(DATA_URL_1)
>>> # Does not execute the function. Instead, returns its previously computed
>>> # value. This means that now the data in d1 is the same as in d2.
>>>
>>> d3 = fetch_and_clean_data(DATA_URL_2)
>>> # This is a different URL, so the function executes.

To set the persist parameter, use this command as follows:

>>> @st.cache(persist=True)
... def fetch_and_clean_data(url):
...     # Fetch data from URL here, and then clean it up.
...     return data

To disable hashing return values, set the allow_output_mutation parameter to True:

>>> @st.cache(allow_output_mutation=True)
... def fetch_and_clean_data(url):
...     # Fetch data from URL here, and then clean it up.
...     return data

To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. MongoClient) to a hash function (id) like this:

>>> @st.cache(hash_funcs={MongoClient: id})
... def connect_to_database(url):
...     return MongoClient(url)

Alternatively, you can map the type’s fully-qualified name (e.g. “pymongo.mongo_client.MongoClient”) to the hash function instead:

>>> @st.cache(hash_funcs={"pymongo.mongo_client.MongoClient": id})
... def connect_to_database(url):
...     return MongoClient(url)

Pre-release features

At Streamlit, we like to move quick while keeping things stable. In our latest effort to move even faster without sacrificing stability, we’re offering our bold and fearless users two ways to try out Streamlit’s bleeding-edge features:

  1. Nightly releases

  2. Beta and experimental features

Nightly releases

At the end of each day (at night 🌛), our bots run automated tests against the latest Streamlit code and, if everything looks good, it publishes them as the streamlit-nightly package. This means the nightly build includes all our latest features, bug fixes, and other enhancements on the same day they land on our codebase.

How does this differ from official releases?

Official Streamlit releases go not only through both automated tests but also rigorous manual testing, while nightly releases only have automated tests. It’s important to keep in mind that new features introduced in nightly releases often lack polish. In our official releases, we always make double-sure all new features are ready for prime time.

How do I use the nightly release?

All you need to do is install the streamlit-nightly package:

pip uninstall streamlit
pip install streamlit-nightly --upgrade

Warning

You should never have both streamlit and streamlit-nightly installed in the same environment!

Why should I use the nightly release?

Because you can’t wait for official releases, and you want to help us find bugs early!

Why shouldn’t I use the nightly release?

While our automated tests have high coverage, there’s still a significant likelihood that there will be some bugs in the nightly code.

Can I choose which nightly release I want to install?

If you’d like to use a specific version, you can find the version number in our Release history. Specify the desired version using pip as usual: pip install streamlit-nightly==x.yy.zz-123456.

Can I compare changes between releases?

If you’d like to review the changes for a nightly release, you can use the comparison tool on GitHub.

Beta and Experimental Features

In addition to nightly releases, we also have two naming conventions for less stable Streamlit features: st.beta_ and st.experimental_. These distinctions are prefixes we attach to our function names to make sure their status is clear to everyone.

Here’s a quick rundown of what you get from each naming convention:

  • st: this is where our core features like st.write and st.dataframe live. If we ever make backward-incompatible changes to these, they will take place gradually and with months of announcements and warnings.

  • beta_: this is where all new features land before they becoming part of Streamlit core. This gives you a chance to try the next big thing we’re cooking up weeks or months before we’re ready to stabilize its API.

  • experimental_: this is where we’ll put features that may or may not ever make it into Streamlit core. We don’t know whether these features have a future, but we want you to have access to everything we’re trying, and work with us to figure them out.

The main difference between beta_ and experimental_ is that beta features are expected to make it into Streamlit core at some point soon, while experimental features may never make it.

Beta

Features with the beta_ naming convention are all scheduled to become part of Streamlit core. While in beta, a feature’s API and behaviors may not be stable, and it’s possible they could change in ways that aren’t backward-compatible.

The lifecycle of a beta feature

  1. A feature is added with the beta_ prefix.

  2. The feature’s API stabilizes and the feature is cloned without the beta_ prefix, so it exists as both st and beta_. At this point, users will see a warning when using the version of the feature with the beta_ prefix – but the feature will still work.

  3. At some point, the code of the beta_-prefixed feature is removed, but there will still be a stub of the function prefixed with beta_ that shows an error with appropriate instructions.

  4. Finally, at a later date the beta_ version is removed.

Experimental

Features with the experimental_ naming convention are things that we’re still working on or trying to understand. If these features are successful, at some point they’ll become part of Streamlit core, by moving to the beta_ naming convention and then to Streamlit core. If unsuccessful, these features are removed without much notice.

Warning

Experimental features and their APIs may change or be removed at any time.

The lifecycle of an experimental feature

  1. A feature is added with the experimental_ prefix.

  2. The feature is potentially tweaked over time, with possible API/behavior breakages.

  3. At some point, we either promote the feature to beta_ or remove it from experimental_. Either way, we leave a stub in experimental_ that shows an error with instructions.