Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Text, Data and Charts

Metrics and Status Elements

Show KPIs with st.metric and deltas, give feedback with success, info, warning and error boxes, and show long-running work with progress, spinner, status and toast.

A good data app answers two questions at a glance: "how are we doing?" and "is something happening or wrong?" Streamlit has dedicated elements for each. st.metric shows a number with its change. Status boxes (st.success, st.info, st.warning, st.error) communicate the state of things. And st.progress, st.spinner, st.status and st.toast keep the user informed during slow work.

The Streamlit code is real and read-only, with the visible result described. Runnable blocks calculate the values you would pass to these elements and imitate the progress behavior with plain Python.

st.metric: a number with a trend

A metric card has a label, a big value, and an optional delta, the change compared with some baseline.

Python
import streamlit as st

st.metric(label="Revenue", value="$12,480", delta="$850")
st.metric(label="Churn", value="3.1%", delta="-0.4%", delta_color="inverse")
st.metric(label="Servers", value=24, delta=0)

The first card shows "Revenue", a large "$12,480" and a small green up-arrow with "$850". The second shows "3.1%" with a delta of -0.4%; because delta_color="inverse" flips the meaning, a drop in churn is shown in green (down is good). The third shows 24 with a grey, neutral delta of 0.

Argument Meaning
label Name above the number
value The number or string shown large
delta Change: a number or string; a leading minus makes it a decrease
delta_color "normal" (up green, down red), "inverse" (the opposite), "off" (gray)
help Tooltip text on a question-mark icon
border=True Draw a card outline around the metric
chart_data A list or series to show as a small sparkline behind the number

Streamlit does not compute the delta for you, so the arithmetic belongs in your script. Strings and numbers both work; a number is shown as written, so format it first (see Text Elements).

Metrics are most useful in a row of columns (see Columns and Containers):

Python
a, b, c = st.columns(3)
a.metric("Revenue", "$12,480", "$850", border=True)
b.metric("Orders", "312", "-14", border=True)
c.metric("Avg. basket", "$40.0", "$1.2", border=True)

Compute the numbers: runnable pandas

The logic behind a metric is a comparison between the latest period and the previous one. Try it with daily data:

Python Compute a metric and its delta

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You would pass f"${latest['revenue']:,}" as value and f"{revenue_delta:+,}" as delta; the sparkline list goes into chart_data.

Status boxes

Four colored message boxes explain what happened. Each takes Markdown text and an optional icon:

Python
import streamlit as st

st.success("Upload complete. 1,204 rows imported.")
st.info("Tip: filters apply to every chart on this page.")
st.warning("3 rows had missing dates and were skipped.")
st.error("Could not connect to the database.")

The page shows a green box, a blue box, a yellow box and a red box, each with an icon. Choose by meaning: success for done, info for neutral help, warning for something the user should check, error for failure. st.exception(e) shows an exception with its traceback, useful in a try/except:

Python
try:
    result = 10 / int(st.text_input("Divide 10 by", "0"))
    st.write(result)
except ZeroDivisionError as e:
    st.error("Division by zero is not allowed.")

Prefer a clear st.error message over a raw traceback for end users; keep st.exception for developer tools.

Progress, spinner and status

Slow work should never leave the page looking frozen.

Python
import time
import streamlit as st

# 1. a progress bar
bar = st.progress(0, text="Starting...")
for i in range(100):
    time.sleep(0.02)
    bar.progress(i + 1, text=f"Processing {i + 1}%")
bar.empty()                      # remove the bar when done

# 2. a spinner around one slow call
with st.spinner("Training model..."):
    time.sleep(2)
st.success("Done!")

# 3. a status container that collects steps
with st.status("Loading data", expanded=True) as status:
    st.write("Reading files...")
    time.sleep(1)
    st.write("Cleaning...")
    status.update(label="Data ready", state="complete", expanded=False)

The first part shows a bar that fills while its text changes from "Processing 1%" to "Processing 100%", then vanishes. st.progress accepts an integer from 0 to 100 or a float from 0.0 to 1.0. The second shows a small spinning icon with the message while the with block runs, then the green success box. The third shows a box titled "Loading data" listing each step; at the end it collapses and its label becomes "Data ready" with a checkmark.

Two practical notes. Every bar.progress call updates the same element, not a new one, so it is cheap. And while a script is busy, the rest of the page that was already sent stays visible, so put the progress element where the user will look.

Imitating progress (stand-in)

The block below is not Streamlit. It shows the idea of an element that is created once and updated repeatedly, using a text bar printed in the console.

Python Stand-in: update one element repeatedly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Toasts and celebrations

st.toast("Saved!", icon="โœ…") pops up a brief message in a corner that disappears by itself. It does not take space in the page, so it is ideal for confirmations after a button click. st.balloons() and st.snow() shower the page with a short animation; fun for a finished form, but do not overuse them.

Choose a status from your data

Often the box type depends on a number. Keep that rule in a small function so you can test it without a server:

Python Pick the right status message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the app: kind, message = status_for(...) then getattr(st, kind)(message).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You show churn with delta='-0.4%'. Lower churn is good. Which argument makes the drop green?

    'inverse' swaps the colors so a decrease is shown as good (green).
  2. 2. Which element shows a short message that disappears by itself in a corner?

    st.toast is a temporary pop-up notification.
  3. 3. What value range does st.progress accept?

    An int from 0 to 100 or a float from 0.0 to 1.0 sets the fill.
  4. 4. Who calculates the delta for st.metric?

    st.metric only displays the value and delta you give it.

Summary

  • st.metric shows a labelled value with a delta, color rule and optional sparkline; compute the delta yourself.
  • success, info, warning and error give colored feedback; exception shows a traceback.
  • progress, spinner, status and toast keep users informed about slow work.
  • Keep status rules in small functions that you can test as plain Python.

Next: Built-in Charts