Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Text, Data and Charts

Matplotlib, Altair and Plotly in Streamlit

Use st.pyplot, st.altair_chart and st.plotly_chart for full control over charts. Learn figure functions, the object-oriented Matplotlib API, caching figures and choosing a library.

The built-in charts from the previous lesson cover the basics. Sooner or later you need a histogram with chosen bins, a heatmap, annotations, a dual axis or a chart in a very specific style. Streamlit does not reinvent plotting libraries; it displays the charts they make. This lesson covers the three you will use most: Matplotlib through st.pyplot, Altair through st.altair_chart, and Plotly through st.plotly_chart.

The Streamlit calls are real and read-only. The Matplotlib figure functions run in your browser here, because writing a function that returns a figure is the most important habit when building such apps.

Matplotlib with st.pyplot

Matplotlib is the long-standing standard. Build a figure in Python, then hand it to Streamlit:

Python
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st

bins = st.slider("Number of bins", 5, 50, 20)

rng = np.random.default_rng(1)
values = rng.normal(loc=50, scale=10, size=1000)

fig, ax = plt.subplots()
ax.hist(values, bins=bins)
ax.set_xlabel("Value")
ax.set_ylabel("Count")
st.pyplot(fig)

The page shows a slider and, below it, a histogram drawn as a static image. Move the slider to 40 and the script reruns; the histogram is redrawn with thinner bars. A Matplotlib figure is an image, so there are no tooltips or zoom, but you have full control over every detail.

Matplotlib rules for Streamlit

  1. Use the object-oriented API. Create the figure with fig, ax = plt.subplots() and call methods on ax. The global plt.plot(...) style works on a hidden "current figure" shared by all users of the server, so two sessions can scribble on each other's chart.
  2. Pass the figure explicitly: st.pyplot(fig). Streamlit does not call plt.show().
  3. Close figures you no longer need. Every rerun creates a new figure, and figures that are never closed pile up in memory (Matplotlib even warns after 20 open figures). Call plt.close(fig) after st.pyplot(fig) in long-running apps.
  4. Cache the expensive part (loading and computing) with the tools from the State and Caching chapter, and redraw the figure on each run: drawing is cheap compared to computing.
  5. Set a size with figsize=(6, 3.5); otherwise the picture may look huge in a narrow column.

A figure function you can run

Put drawing code in a function that takes a DataFrame and options and returns a Figure. It is easy to test, easy to reuse on several pages, and a real app simply calls st.pyplot(make_figure(...)).

Python A function that returns a Matplotlib figure

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.

Change bins to 40 and run again. In the app, the slider gives the number and the same function does the rest.

Altair with st.altair_chart

Altair is a declarative library: you describe what you want ("bars of units by drink, colored by region") instead of drawing step by step. It produces interactive Vega-Lite charts that Streamlit renders natively, with tooltips and zoom.

Python
import altair as alt
import pandas as pd
import streamlit as st

df = pd.DataFrame({
    "drink": ["Tea", "Coffee", "Juice", "Water"] * 2,
    "region": ["North"] * 4 + ["South"] * 4,
    "units": [120, 310, 80, 150, 90, 260, 110, 170],
})

chart = (
    alt.Chart(df)
    .mark_bar()
    .encode(
        x=alt.X("drink:N", sort="-y", title="Drink"),
        y=alt.Y("sum(units):Q", title="Units sold"),
        color="region:N",
        tooltip=["drink", "region", "units"],
    )
)
st.altair_chart(chart, use_container_width=True)

The page shows vertical bars stacked by region, with the tallest drink first (sort="-y") and a legend for the two regions. Hover a segment to see its tooltip. The type suffixes after the colon tell Altair what a column is: :Q quantitative (numbers), :N nominal (categories), :O ordinal (ordered categories), :T temporal (dates). Altair is where you go when you need an exact category order, small multiples (facet), layered charts, or interaction. Newer Streamlit versions let you capture clicks and brush selections from Altair charts with on_select="rerun" and read the selected data in Python.

Plotly with st.plotly_chart

Plotly makes rich, interactive charts (3D scatter, sunbursts, candlesticks, choropleth maps). Plotly Express creates a figure in one line:

Python
import plotly.express as px
import streamlit as st

df = px.data.gapminder().query("year == 2007")
fig = px.scatter(
    df,
    x="gdpPercap",
    y="lifeExp",
    size="pop",
    color="continent",
    hover_name="country",
    log_x=True,
)
st.plotly_chart(fig)

The page shows a bubble chart with one bubble per country, colored by continent, with a toolbar for zoom, pan and "download as PNG". Hovering shows the country's name and values. Plotly's chart code is about the same in every app: build a fig, optionally call fig.update_layout(...), pass it to st.plotly_chart. Plotly figures are larger than Altair ones, so avoid sending tens of thousands of points.

Other options

  • st.vega_lite_chart(df, spec) accepts a raw Vega-Lite JSON spec.
  • st.pydeck_chart draws deck.gl maps (3D columns, arcs, heatmaps).
  • Seaborn is built on Matplotlib: draw with sns.histplot(..., ax=ax) and show with st.pyplot(fig).
  • Bokeh and other libraries are available through community components.

Choosing a library

You want Use
A quick standard chart built-in st.line_chart and friends
Pixel-level control, scientific plots, static images Matplotlib or Seaborn
Declarative, concise, interactive, small multiples Altair
Rich interactivity, 3D, many chart types Plotly

These libraries must be listed in your requirements.txt (matplotlib, altair, plotly). Altair ships with Streamlit's dependencies; Plotly and Matplotlib are separate installs depending on the version. If an import fails when you deploy, a missing requirement is the usual reason.

Prepare data for any chart

All three libraries want tidy data. A typical pre-chart step aggregates and sorts. That logic is the same regardless of the library, and it runs here:

Python Aggregate and sort before charting

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.

Coffee comes first with 570 units, then Water, Tea and Juice. The stacked bars show each region's part. This matches the Altair example above, which does the grouping inside the chart specification instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should Streamlit apps use fig, ax = plt.subplots() rather than plt.plot()?

    The global 'current figure' is shared across the server process, so concurrent sessions could draw on each other's figure. An explicit figure object is yours alone.
  2. 2. What does st.pyplot(fig) display?

    A Matplotlib figure is rendered as an image.
  3. 3. In Altair, what does the :Q suffix in 'units:Q' mean?

    :Q = quantitative, :N = nominal, :O = ordinal, :T = temporal.
  4. 4. Which library is best when you need an exact category order and small multiples?

    Altair's declarative encoding gives explicit control over sort order, facets and layers.

Summary

  • st.pyplot(fig), st.altair_chart(chart) and st.plotly_chart(fig) display charts from the big libraries.
  • Use Matplotlib's object-oriented API in Streamlit and keep drawing code in functions that return figures.
  • Altair is declarative and great for sorted, layered or faceted charts; Plotly is great for rich interactivity.
  • List chart libraries in requirements.txt and prepare tidy data with pandas first.

Next: Buttons and Toggles