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

How it works is simple: 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 on Python 3.

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 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. Inline and block math are supported by KaTeX and remark-math.

    The body also support LaTeX expressions, by just wrapping them in “$” or “$$” (the “$$” must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html.

  • 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.
    • 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 simplest use case is to draw Markdown-formatted text, whenever the input is a string:

>>> write('Hello, *World!*')
(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')
>>>
>>> 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 just 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)

Display a line 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, dict) – or None Data to be plotted.
  • width (int) – The chart width in pixels, or 0 for full width.
  • height (int) – The chart width in pixels, or 0 for default height.

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)

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, or 0 for full width.
  • height (int) – The chart width in pixels, or 0 for default height.

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)

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, or 0 for full width.
  • height (int) – The chart width in pixels, or 0 for default height.

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, **kwargs)

Display a matplotlib.pyplot figure.

Parameters:
  • fig (Matplotlib Figure) – The figure to plot. When this argument isn’t specified, which is the usual case, this function will render the global plot.
  • **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)
>>> plt.hist(arr, bins=20)
>>>
>>> st.pyplot()
(view standalone Streamlit app)

Notes

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, width=0)

Display a chart using the Altair library.

Parameters:
  • altair_chart (altair.vegalite.v2.api.Chart) – The Altair chart object to display.
  • width (number) – If 0 (default), stretch chart to the full document width. If -1, use the default from Altair. If greater than 0, sets the width. Note that if the top-level width is defined, it takes precedence over this argument.

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')
>>>
>>> st.altair_chart(c, width=-1)
(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, width=0, **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.
  • width (number) – If 0 (default), stretch chart to the full document width. If -1, use the default from Vega-Lite. If greater than 0, sets the width. Note that if spec[‘width’] is defined, it takes precedence over this argument.
  • **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': 'circle',
...     '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, width=0, height=0, 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, or matplotlib.figure.Figure

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

    If a Matplotlib Figure, converts it to a Plotly figure and displays it.

  • width (int) – The chart width in pixels, or 0 for full width.
  • height (int) – The chart height in pixels, or 0 for default height.
  • 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, just 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)
(view standalone Streamlit app)
streamlit.bokeh_chart(figure)

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.

To show Bokeh charts in Streamlit, just call st.bokeh_chart wherever you would call Bokeh’s show.

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)
(view standalone Streamlit app)
streamlit.deck_gl_chart(spec=None, **kwargs)

Draw a map chart using the Deck.GL library.

This API closely follows Deck.GL’s JavaScript API (https://deck.gl/#/documentation), with a few small adaptations and some syntax sugar.

Parameters:
  • spec (dict) –

    Keys in this dict can be:

    • Anything accepted by Deck.GL’s top level element, such as “viewport”, “height”, “width”.
    • ”layers”: a list of dicts containing information to build a new Deck.GL layer in the map. Each layer accepts the following keys:
      • ”data” : DataFrame The data for the current layer.
      • ”type” : str One of the Deck.GL layer types that are currently supported by Streamlit: ArcLayer, GridLayer, HexagonLayer, LineLayer, PointCloudLayer, ScatterplotLayer, ScreenGridLayer, TextLayer.
      • ”encoding” : dict A mapping connecting specific fields in the dataset to properties of the chart. The exact keys that are accepted depend on the “type” field, above.

        For example, Deck.GL”s documentation for ScatterplotLayer shows you can use a “getRadius” field to individually set the radius of each circle in the plot. So here you would set “encoding”: {“getRadius”: “my_column”} where “my_column” is the name of the column containing the radius data.

        For things like “getPosition”, which expect an array rather than a scalar value, we provide alternates that make the API simpler to use with dataframes:

        • Instead of “getPosition” : use “getLatitude” and “getLongitude”.
        • Instead of “getSourcePosition” : use “getLatitude” and “getLongitude”.
        • Instead of “getTargetPosition” : use “getTargetLatitude” and “getTargetLongitude”.
        • Instead of “getColor” : use “getColorR”, “getColorG”, “getColorB”, and (optionally) “getColorA”, for red, green, blue and alpha.
        • Instead of “getSourceColor” : use the same as above.
        • Instead of “getTargetColor” : use “getTargetColorR”, etc.
      • Plus anything accepted by that layer type. For example, for ScatterplotLayer you can set fields like “opacity”, “filled”, “stroked”, and so on.
  • **kwargs (any) – Same as spec, but as keywords. Keys are “unflattened” at the underscore characters. For example, foo_bar_baz=123 becomes foo={‘bar’: {‘bar’: 123}}.

Example

For convenience, if you pass in a dataframe and no spec, you get a scatter plot:

>>> df = pd.DataFrame(
...    np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
...    columns=['lat', 'lon'])
...
>>> st.deck_gl_chart(layers = [{
        'data': df,
        'type': 'ScatterplotLayer'
    }])
(view standalone Streamlit app)

The dataframe must have columns called ‘lat’/’latitude’ or ‘lon’/’longitude’.

If you want to do something more interesting, pass in a spec with its own data, and no top-level dataframe. For instance:

>>> st.deck_gl_chart(
...     viewport={
...         'latitude': 37.76,
...         'longitude': -122.4,
...         'zoom': 11,
...         'pitch': 50,
...     },
...     layers=[{
...         'type': 'HexagonLayer',
...         'data': df,
...         'radius': 200,
...         'elevationScale': 4,
...         'elevationRange': [0, 1000],
...         'pickable': True,
...         'extruded': True,
...     }, {
...         'type': 'ScatterplotLayer',
...         'data': df,
...     }])
...
(view standalone Streamlit app)
streamlit.graphviz_chart(figure_or_dot, width=0, height=0)

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
  • width (type) – The chart width in pixels, or 0 for full width.
  • height (type) – The chart height in pixels, or 0 for default height.

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, zoom=None)

Display a map with points on it.

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

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)
streamlit.image(image, caption=None, width=None, use_column_width=False, clamp=False, channels='RGB', format='JPEG')

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 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.
  • use_column_width (bool) – If True, set the image width to the column width. This overrides 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.
  • format ('JPEG' or 'PNG') – This parameter specifies the image format to use when transferring the image data. Defaults to ‘JPEG’.

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 or a string with a URL pointing to the file to load. If passing the raw data, this must include headers and any other bytes required in the actual file.
  • 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 or a string with a URL pointing to the video to load. Includes support for YouTube URLs. If passing the raw data, this must include headers and any other bytes required in the actual file.
  • 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)

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, or pandas.Series) – Labels for the radio options. This will be cast to str internally by default.
  • index (int) – The index of the preselected option on first render.
  • 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:

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, or pandas.Series) – Labels for the select options. This will be cast to str internally by default.
  • 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, or pandas.Series) – Labels for the select options. This will be cast to str internally by default.
  • 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',
        ('Yellow', 'Red')
...     ('Green', 'Yellow', 'Red', 'Blue'))
>>>
>>> st.write('You selected:', options)
streamlit.slider(label, min_value=None, max_value=None, value=None, step=None, format=None, key=None)

Display a slider widget.

Parameters:
  • label (str or None) – A short label explaining to the user what this slider is for.
  • min_value (int/float or None) – The minimum permitted value. Defaults to 0 if the value is an int, 0.0 otherwise.
  • max_value (int/float or None) – The maximum permitted value. Defaults 100 if the value is an int, 1.0 otherwise.
  • value (int/float or a tuple/list of int/float or None) – The value of this widget when it first renders. In case the value is passed as a tuple/list a range slider will be used. Defaults to min_value.
  • step (int/float or None) – The stepping interval. Defaults to 1 if the value is an int, 0.01 otherwise.
  • format (str or None) – Printf/Python format string controlling how the interface should display numbers. This does not impact the return value.
  • 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 or tuple of int/float

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 selector:

>>> values = st.slider(
...     'Select a range of values',
...     0.0, 100.0, (25.0, 75.0))
>>> st.write('Values:', values)
streamlit.text_input(label, value='', key=None)

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.
  • 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

>>> 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.DeltaGenerator.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 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) – Printf/Python format string controlling how the interface should display numbers. This does not impact the return value.
  • 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='', 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.
  • 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, 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/datetime.datetime) – The value of this widget when it first renders. This will be cast to str internally. Defaults to today.
  • 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)

Add widgets to sidebar

Not only can you add interactivity to your report with widgets, you can organize them into a sidebar with st.write.[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.write (you should use st.sidebar.markdown() instead), st.echo, and st.spinner.

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

import streamlit as st

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

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()

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

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) – The percentage complete: 0 <= value <= 100

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):
...     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, exception_traceback=None)

Display an exception.

Parameters:
  • exception (Exception) – The exception to display.
  • exception_traceback (Exception Traceback or None) – If None or False, does not show display the trace. If True, tries to capture a trace automatically. If a Traceback object, displays the given traceback.

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()

Add a placeholder to the app.

The placeholder can be filled any time by calling methods on the return value.

Example

>>> my_placeholder = st.empty()
>>>
>>> # Now replace the placeholder with some text:
>>> my_placeholder.text("Hello world!")
>>>
>>> # And replace the text with an image:
>>> my_placeholder.image(my_image_bytes)
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.

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.

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.

streamlit.cache(func=None, persist=False, allow_output_mutation=False, show_spinner=True, suppress_st_warning=False, **kwargs)

Function decorator to memoize function executions.

Parameters:
  • func (callable) – The function to cache. Streamlit hashes the function and dependent code. Streamlit can only hash nested objects (e.g. bar in foo.bar) in Python 3.4+.
  • 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.

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. Just 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