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 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 simplest 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 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, use_container_width=True)

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. 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, which is the usual case, this function will render the global plot.

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

  • width (number) – Deprecated. If != 0 (default), will show an alert. From now on you should set the width directly in the Altair spec. Please refer to the Altair documentation for details.

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

  • width (number) – Deprecated. If != 0 (default), will show an alert. From now on you should set the width directly in the Vega-Lite spec. Please refer to the Vega-Lite documentation for details.

  • 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, width=0, height=0, 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.

  • width (int) – Deprecated. If != 0 (default), will show an alert. From now on you should set the width directly in the figure. Please refer to the Plotly documentation for details.

  • height (int) – Deprecated. If != 0 (default), will show an alert. From now on you should set the height directly in the figure. Please refer to the Plotly documentation for details.

  • 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, 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, 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, just 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.deck_gl_chart(spec=None, use_container_width=False, **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.

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

      • Plus anything accepted by that layer type. The exact keys that are accepted depend on the “type” field, above. For example, for ScatterplotLayer you can set fields like “opacity”, “filled”, “stroked”, and so on.

        In addition, 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 “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.

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

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

>>> 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, 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

  • width (number) – Deprecated. If != 0 (default), will show an alert. From now on you should set the width directly in the Graphviz spec. Please refer to the Graphviz documentation for details.

  • height (number) – Deprecated. If != 0 (default), will show an alert. From now on you should set the height directly in the Graphviz spec. Please refer to the Graphviz documentation for details.

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

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.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=datetime.datetime(1, 1, 1, 0, 0), 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 datetime.min.

  • 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, 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’] By default, all extensions are allowed.

  • encoding (str or None) – The encoding to use when opening textual files (i.e. non-binary). For example: ‘utf-8’. If set to ‘auto’, will try to guess the encoding. If None, will assume the file is binary.

  • 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 no file has been uploaded, returns None. Otherwise, returns the data for the uploaded file(s): - If the file is in a well-known textual format (or if the encoding parameter is set), the file data is a StringIO. - Otherwise the file data is BytesIO. - If multiple_files is True, a list of file data will be returned.

Note that BytesIO/StringIO are “file-like”, which means you can pass them anywhere where a file is expected!

Return type

BytesIO or StringIO or or list of BytesIO/StringIO or None

Examples

>>> uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
>>> if uploaded_file is not None:
...     data = pd.read_csv(uploaded_file)
...     st.write(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/pre_release_features.html 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 excecution immediately. Streamlit will not run any statements after st.stop(). We recommend rendering an informational message that would explain the stop in execution. When run outside of Streamlit, it will raise an Exception

Example

>>> name = st.text_input('Name')
>>> if not name:
>>>   st.warning('Please input a name.')
>>>   st.stop()
>>> st.succcess('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.write (you should use st.sidebar.markdown() instead), 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")
)

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

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.

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/pre_release_features.html 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. 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

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)