Shiny for Python: A Reactive Dashboard with Plots, Value Boxes and Tables

Build a Shiny for Python dashboard with Express syntax: a sidebar, a reactive plot, value boxes, a data table, a calculation shared with reactive.calc, and a button that controls when the chart updates.

To build a dashboard in Shiny for Python, put inputs such as ui.input_slider() in a sidebar, write a function decorated with @render.plot that reads them as input.name(), and start the file with shiny run app.py. Shiny tracks which inputs each output reads and reruns only the outputs that depend on what changed. The version in this post is Shiny 1.9 with the Express syntax. For how it differs from Streamlit and Dash, see the framework comparison.

Install it with pip install shiny. The apps below also use numpy, pandas and matplotlib.

Quick Example

The data is simulated daily visitor counts from trail counters on four trails over 180 days (seeded, so you get the same numbers). Save this as app.py and run shiny run app.py, then open http://127.0.0.1:8000:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from shiny import reactive
from shiny.express import input, render, ui

rng = np.random.default_rng(511)
days = pd.date_range("2026-04-01", periods=180, name="date")
base = {"Ridge": 140, "Lakeshore": 220, "Canyon": 90, "Meadow": 170}
frames = []
for trail, level in base.items():
    weekend = np.where(days.dayofweek >= 5, 1.8, 1.0)
    season = 1 + 0.35 * np.sin((days.dayofyear - 100) / 365 * 2 * np.pi * 1.6)
    visitors = rng.poisson(level * weekend * season)
    frames.append(pd.DataFrame({"date": days, "trail": trail, "visitors": visitors}))
counts = pd.concat(frames, ignore_index=True)
COLORS = {"Ridge": "#1b9e77", "Lakeshore": "#7570b3", "Canyon": "#d95f02", "Meadow": "#e6ab02"}

ui.page_opts(title="Trail Counters")

with ui.sidebar():
    ui.input_checkbox_group("trails", "Trails", list(base), selected=list(base))
    ui.input_slider("window", "Smoothing window (days)", 1, 30, 7)

@render.plot
def chart():
    fig, ax = plt.subplots()
    for trail in input.trails():
        series = counts[counts["trail"] == trail].set_index("date")["visitors"]
        ax.plot(series.rolling(input.window()).mean(),
                label=trail, color=COLORS[trail])
    ax.set_ylabel("Visitors per day")
    ax.legend(frameon=False)
    fig.autofmt_xdate()
    return fig

Shiny app with a sidebar of trail checkboxes and a smoothing slider next to a line chart of daily visitors on four trails

Everything is plain Python in one file. Three things to know:

  • Inputs are functions. input.window() returns the slider's current value, and calling it inside an output is what registers the dependency. Reading input.window without the parentheses does nothing.
  • Outputs are decorated functions. The function name (chart) is the output's ID. @render.plot accepts a Matplotlib figure, and the figure is drawn in the page where the function is defined.
  • The file runs once per browser session, not once per input change. The data setup is not rerun when a slider moves. Only chart() reruns.

How do I share one calculation between outputs?

When a chart, a few numbers and a table all need the same filtered data, compute it once in a function decorated with @reactive.calc. Each output calls it like a function, and Shiny caches the result until one of its inputs changes. Add a date range to the sidebar, then replace everything below the data setup with this:

from shiny import reactive
from shiny.express import input, render, ui

ui.page_opts(title="Trail Counters", fillable=True)

with ui.sidebar(width=300):
    ui.input_checkbox_group("trails", "Trails", list(base), selected=list(base))
    ui.input_date_range("dates", "Dates", start=days[0], end=days[-1],
                        min=days[0], max=days[-1])

@reactive.calc
def selected():
    start, end = input.dates()
    keep = counts["trail"].isin(input.trails())
    keep &= (counts["date"] >= pd.Timestamp(start)) & (counts["date"] <= pd.Timestamp(end))
    return counts[keep]

with ui.layout_columns(fill=False):
    with ui.value_box():
        "Total visitors"
        @render.text
        def total():
            return f"{selected()['visitors'].sum():,}"

    with ui.value_box():
        "Busiest day"
        @render.text
        def busiest():
            daily = selected().groupby("date")["visitors"].sum()
            return f"{daily.idxmax():%b %d} ({daily.max():,})" if len(daily) else "none"

with ui.layout_columns(col_widths=[6, 6]):
    with ui.card():
        ui.card_header("Weekly visitors")

        @render.plot
        def chart():
            weekly = (selected().groupby([pd.Grouper(key="date", freq="W"), "trail"])["visitors"]
                      .sum().unstack())
            fig, ax = plt.subplots()
            weekly.plot(ax=ax, color=[COLORS[t] for t in weekly.columns])
            ax.set_xlabel("")
            ax.set_ylabel("Visitors per week")
            ax.set_ylim(top=3400)  # headroom for the legend
            ax.legend(frameon=False, ncol=2, loc="upper right")
            return fig

    with ui.card():
        ui.card_header("By trail")

        @render.data_frame
        def table():
            summary = selected().groupby("trail")["visitors"].agg(["sum", "mean", "max"])
            summary.columns = ["Total", "Daily average", "Peak day"]
            summary = summary.round(0).astype(int).rename_axis("Trail").reset_index()
            return render.DataGrid(summary, width="100%")

Shiny dashboard with two value boxes showing total visitors (146,945) and the busiest day (May 30, 1,588), a weekly line chart in a card and a table of totals by trail

Over the full 180 days the four trails counted 146,945 visitors, the busiest day was May 30 with 1,588, and Lakeshore alone was 51,956 of the total (35%). selected() runs once per change, even though four outputs read it. Uncheck a trail and all four update. Narrow the date range and only the outputs that depend on input.dates() (through selected()) rerun.

A few details that trip people up:

  • The reactive.calc function can only be called from a reactive context such as a @render function or another @reactive.calc. Calling selected() at the top level of the file raises a RuntimeError.
  • Value boxes take their title as a bare string and the value as a @render.text output inside the same with block.
  • render.DataGrid gives a sortable table, and render.DataTable is the same idea with different styling. @render.table is a plain HTML table.
  • Handle empty selections. Unchecking every trail gives selected() zero rows, and idxmax() on an empty series raises an error. That is why busiest() has the if len(daily) check.

How do I update an output only when a button is clicked?

By default every output reruns on every input change. To wait for a button, add @reactive.event(input.go) under the render decorator. The function then depends only on the button, and it can read the other inputs without being triggered by them:

from shiny import reactive
from shiny.express import input, render, ui

ui.page_opts(title="Trail Counters")

with ui.sidebar():
    ui.input_checkbox_group("trails", "Trails", list(base), selected=list(base))
    ui.input_slider("window", "Smoothing window (days)", 1, 30, 7)
    ui.input_action_button("go", "Update chart")

@render.plot
@reactive.event(input.go, ignore_none=False)
def chart():
    fig, ax = plt.subplots()
    for trail in input.trails():
        series = counts[counts["trail"] == trail].set_index("date")["visitors"]
        ax.plot(series.rolling(input.window()).mean(),
                label=trail, color=COLORS[trail])
    ax.set_ylabel("Visitors per day")
    ax.legend(frameon=False)
    fig.autofmt_xdate()
    return fig

Moving the slider now changes nothing until you press the button. ignore_none=False makes the chart draw once when the page loads. Without it, the output stays empty until the first click. This is useful for slow computations or model runs, where redrawing on every slider step would be wasteful.

What is the difference between Shiny Express and Shiny Core?

The apps above use Express, where the file runs top to bottom, with blocks build the layout, and decorated functions become outputs. Shiny Core is the original syntax, with a separate UI object and a server function. The Core version of the quick example uses the same data setup, but without the from shiny.express import ... line (an app that imports shiny.express and also defines app = App(...) raises a RuntimeError):

from shiny import App, render, ui

app_ui = ui.page_sidebar(
    ui.sidebar(
        ui.input_checkbox_group("trails", "Trails", list(base), selected=list(base)),
        ui.input_slider("window", "Smoothing window (days)", 1, 30, 7),
    ),
    ui.output_plot("chart"),
    title="Trail Counters",
)

def server(input, output, session):
    @render.plot
    def chart():
        fig, ax = plt.subplots()
        for trail in input.trails():
            series = counts[counts["trail"] == trail].set_index("date")["visitors"]
            ax.plot(series.rolling(input.window()).mean(),
                    label=trail, color=COLORS[trail])
        ax.set_ylabel("Visitors per day")
        ax.legend(frameon=False)
        fig.autofmt_xdate()
        return fig

app = App(app_ui, server)
Express Core
Layout with ui.sidebar(): blocks in the file ui.page_sidebar(...) object
Output placeholders Created by the decorated function ui.output_plot("chart") in the UI, matched by name
When the code runs The whole file runs again for each new browser session Module-level code runs once at startup. server() runs per session
Good for Small and medium apps, learning Large apps, modules, reusable components

Both syntaxes use the same reactive system and the same input, render and reactive objects, so moving an app from Express to Core means rearranging code, not rewriting it. Start with Express.

Practical Tips

  • Use shiny run app.py --reload during development. The server restarts when you save the file.
  • Create figures inside the render function, as the examples do, so each redraw starts from a clean figure.
  • Keep slow data loading out of an Express app file. The file reruns for every new session, so load a big dataset in a separate module and import it. Python caches imports, so it loads once per server process.
  • Use @reactive.calc for shared work and @reactive.event for button-driven work. Reaching for reactive.effect and mutable state first makes apps hard to follow.
  • Deploying: Shiny apps are ASGI apps, so any host that can run a Python web server works. Posit Connect and shinyapps.io are the Posit-run options.

Similar Topics