marimo: Reactive Python Notebooks with Interactive Charts

Build a reactive marimo notebook with a slider, a dropdown and a Matplotlib chart, select points on an Altair chart to filter a table, and run the notebook as an app.

To make an interactive chart in marimo, create a UI element such as mo.ui.slider(5, 60) in one cell and read its .value in another cell that draws the chart. When the slider moves, marimo reruns every cell that uses it, and only those. marimo is a Python notebook where cells form a dependency graph instead of a script you run top to bottom, and a notebook can be served as a web app with marimo run.

This post uses marimo 0.26 (pip install marimo) and a simulated set of 600 food deliveries in three cities. Notebooks are plain .py files. Save the code below as deliveries.py and run marimo edit deliveries.py to work on it, or marimo run deliveries.py to see it as an app.

Quick Example

import marimo

app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd

    return mo, np, pd, plt


@app.cell
def _(np, pd):
    rng = np.random.default_rng(77)
    n = 600
    city = rng.choice(["Portland", "Denver", "Austin"], n, p=[0.4, 0.3, 0.3])
    distance = rng.gamma(3.0, 1.4, n).round(1)
    slowdown = pd.Series(city).map({"Portland": 1.0, "Denver": 0.85, "Austin": 1.3}).to_numpy()
    minutes = (9 + 3.4 * distance * slowdown + rng.normal(0, 4, n)).clip(min=5).round(1)
    deliveries = pd.DataFrame({"city": city, "distance_km": distance, "minutes": minutes})
    return (deliveries,)


@app.cell
def _(mo):
    city_picker = mo.ui.dropdown(["All", "Portland", "Denver", "Austin"], value="All", label="City")
    bins = mo.ui.slider(5, 60, value=25, label="Bins")
    mo.hstack([city_picker, bins], justify="start")
    return bins, city_picker


@app.cell
def _(bins, city_picker, deliveries, plt):
    shown = deliveries if city_picker.value == "All" else deliveries[deliveries["city"] == city_picker.value]
    fig, ax = plt.subplots(figsize=(8, 3.8))
    ax.hist(shown["minutes"], bins=bins.value, color="#3d5a80", edgecolor="white")
    ax.axvline(shown["minutes"].median(), color="#ee6c4d", linewidth=2)
    ax.set_xlabel("Delivery time (minutes)")
    ax.set_ylabel("Deliveries")
    ax.set_title(f"{city_picker.value}: median {shown['minutes'].median():.0f} min ({len(shown)} deliveries)")
    ax
    return


if __name__ == "__main__":
    app.run()

marimo app with a city dropdown and a bins slider above a histogram of delivery times with a median line

Each @app.cell function is one cell. The arguments are the variables it reads from other cells, and the return is what it defines for them. city_picker and bins are defined in the third cell, so the chart cell lists them as arguments. Dragging the slider changes bins.value, and marimo reruns the chart cell and nothing else. Across all 600 deliveries the median is 22.7 minutes. Choosing a city in the dropdown shows Austin as the slowest (25.4) and Denver as the fastest (19.5). The last expression in a cell (ax here) is what the cell displays.

Compared with a Jupyter notebook, there is no "run all" and no stale output: the picture on screen always matches the code and the widget values. You can also write the cells in any order. marimo works out the order from which cell uses which variable.

How do I select points on a chart and use them in Python?

Wrap an Altair chart in mo.ui.altair_chart(). Dragging a box on the chart selects points, and the .value attribute of the wrapper is a DataFrame of the selected rows. Another cell that reads .value reruns on every selection. Add these cells to the notebook (this one needs pip install altair):

@app.cell
def _(deliveries, mo):
    import altair as alt

    scatter = mo.ui.altair_chart(
        alt.Chart(deliveries)
        .mark_circle(size=40, opacity=0.6)
        .encode(
            x=alt.X("distance_km", title="Distance (km)"),
            y=alt.Y("minutes", title="Delivery time (minutes)"),
            color=alt.Color("city", scale=alt.Scale(range=["#3d5a80", "#ee6c4d", "#5b8e7d"])),
        )
        .properties(width=480, height=300)
    )
    scatter
    return (scatter,)


@app.cell
def _(deliveries, mo, scatter):
    selected = scatter.value
    mo.stop(len(selected) == 0, mo.md("Drag a box on the chart to select deliveries."))
    mo.vstack(
        [
            mo.md(f"**{len(selected)} of {len(deliveries)} deliveries selected**, "
                  f"median {selected['minutes'].median():.0f} minutes"),
            selected.head(4),
        ]
    )
    return

Altair scatter plot of delivery distance and time with a brushed rectangle, above a summary line and a table of the selected deliveries

The screenshot shows a box dragged across the middle of the chart: 294 of the 600 deliveries are inside it, with a median of 29 minutes. Before anything is selected, .value is empty, so the cell uses mo.stop() (explained below) to show a prompt instead of a table of nothing. Click a city in the legend to select that city's points. Passing chart_selection="interval" or "point" forces one kind of selection when marimo's automatic choice is not what you want.

How do I stop a slow cell from rerunning on every change?

Use a mo.ui.run_button() and mo.stop(). mo.stop(condition, output) ends the cell early when the condition is true and shows output instead. With the button's .value as the condition, the expensive code runs only after a click. This cell bootstraps a 95% interval for the median delivery time from 5,000 resamples:

@app.cell
def _(mo):
    boot_button = mo.ui.run_button(label="Bootstrap the median")
    boot_button
    return (boot_button,)


@app.cell
def _(boot_button, deliveries, mo, np):
    mo.stop(not boot_button.value, mo.md("Click the button to resample."))
    boot_rng = np.random.default_rng(1)
    draws = [np.median(boot_rng.choice(deliveries["minutes"], len(deliveries))) for _ in range(5000)]
    low, high = np.percentile(draws, [2.5, 97.5])
    mo.md(f"95% interval for the median delivery time: **{low:.1f} to {high:.1f} minutes**")
    return

With seed 1, the interval is 21.7 to 23.6 minutes, around the sample median of 22.7. Until the button is pressed, the cell shows the prompt and the 5,000 resamples are skipped.

For heavier work, mo.ui.form() wraps an element and holds back its value until the user presses Submit.

How do I run, share or export a marimo notebook?

marimo edit deliveries.py                          # the notebook editor
marimo run deliveries.py                           # a read-only app, code hidden
marimo export html deliveries.py -o deliveries.html  # a static snapshot
marimo convert notebook.ipynb -o notebook.py       # from a Jupyter notebook

marimo run serves the notebook with its widgets live, and visitors cannot edit the code. marimo export html runs the notebook once and saves the output as a static page with no Python behind it, so the sliders do not work there. marimo export html-wasm builds a page that runs the notebook in the browser through WebAssembly, with no Python server.

marimo vs Jupyter vs Streamlit

marimo Jupyter Streamlit
File format Plain .py .ipynb (JSON) Plain .py
Execution Dependency graph, reruns affected cells Cells run in the order you click Whole script reruns
Widgets mo.ui.*, built in ipywidgets, separate install st.*, built in
Turn into an app marimo run Needs Voila or similar streamlit run
Good for Exploration that ends up as an app Free-form exploration Apps from scripts

Streamlit reruns the whole script on every input, while marimo reruns only the cells that depend on the changed value. See Streamlit vs Dash vs Shiny vs Gradio vs Panel for the app frameworks, and the Streamlit guide if you prefer the rerun model.

Practical Tips

  • A variable can be defined in only one cell. Defining df in two cells raises a MultipleDefinitionError. Prefix throwaway names with an underscore (_df) and marimo keeps them local to the cell.
  • Read a widget's .value in a different cell from the one that creates it. marimo raises a RuntimeError if a cell reads the .value of an element it created, because the value could never update.
  • Put the widget and the code that uses it in different cells. Then moving the widget does not rerun the cell that built it.
  • Cells that use plt show the last expression. End a chart cell with ax or fig, not plt.show().

Similar Topics