Plotly

Turn any plotly figure into a two-way input – clicks, hovers, lassos, zooms, legend toggles, and Python-driven animation, with no JavaScript.

Plotly is the chart library most Shiny users reach for first: polished, interactive charts from one line of plotly.express. With @render_plotly, those charts also talk back to your app.

hero

Lasso countries on the left to trace their full history on the right. Try the app.

Installation

pip install 'shinywidgets[plotly]'

Quick start

import plotly.express as px
from shiny.express import ui
from shinywidgets import render_plotly

df = px.data.iris()

ui.page_opts(title="Iris", fillable=True)


@render_plotly
def plot():
    return px.scatter(
        df, x="sepal_width", y="sepal_length", color="species", title="Iris"
    )

quickstart

Return any plotly figure – from plotly.express or graph_objects – and it fills its output. No height settings needed.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Every chart type in plotly.express works the same way.

Reacting to interaction

Every @render_plotly output has methods, called accessors, that report what the user did: plot.clicked(), plot.selected_rows(df), and more. Call one from any reactive context, the same way you’d call input.my_slider(), and that context re-runs whenever the user does it again.

Click for details

import plotly.express as px
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Click for details", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_plotly
        def plot():
            return px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                size="pop",
                size_max=40,
                custom_data=[df.index],
            )

    with ui.card():

        @render.ui
        def detail():
            pts = plot.clicked()
            if pts is None:
                return ui.p("Click a bubble for details.", class_="text-muted")
            # px wraps each point's custom_data in a list; [0] is the row index.
            row = df.loc[pts["customdata"].iloc[0][0]]
            return ui.TagList(
                ui.h4(row["country"]),
                ui.p(f"Continent: {row['continent']}"),
                ui.p(f"Life expectancy: {row['lifeExp']:.1f} years"),
                ui.p(f"GDP per capita: ${row['gdpPercap']:,.0f}"),
                ui.p(f"Population: {row['pop']:,}"),
            )

click detail card

clicked() is None until the first click, then a data frame describing the clicked point. To get from a point back to a row of your data, give the figure custom_data=[df.index]: plotly hands each point’s custom data back, wrapped in a list (one entry per column), so pts["customdata"].iloc[0][0] is the row’s index label.

Lasso to select rows

import plotly.express as px
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Lasso-select countries", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly(listen_to=["selected_rows"])
        def plot():
            fig = px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                custom_data=[df.index],
            )
            fig.update_layout(dragmode="lasso")
            return fig

    with ui.card(full_screen=True):
        ui.card_header("plot.selected_rows(df)")

        @render.data_frame
        def rows():
            cols = ["country", "lifeExp", "gdpPercap"]
            return render.DataGrid(plot.selected_rows(df)[cols].round(1))

selected_rows, pandas

selected_rows(df) does the customdata matching for you and returns the selected rows of df – an empty frame while nothing is selected, so it can go straight into a table.

Selection accessors are opt-in: a lasso over many points produces a large payload, so shinywidgets only sends selections to Python when the renderer asks for them with listen_to=["selected_rows"]. Forgetting it raises an error that names what to add. The same goes for selected(), selecting(), brushing(), and hover(); everything else works with no setup.

For an app that combines both – lasso to filter a table, click for details – start from the lasso explorer template.

Updating in place

When an input changes, the simplest thing is to let the render function re-run. That rebuilds the figure from scratch: the plot goes blank for a moment while it redraws, and the user’s zoom and selection are lost. That’s the right trade when the shape of the figure genuinely changes (new traces, a different chart type).

For everything else – recoloring, resizing markers, moving points – don’t read the input in the render function. Instead, change the figure in place through plot.widget from a @reactive.effect. Updates are instant, and zoom and selection survive:

import plotly.express as px
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Resize markers without rebuilding the plot", fillable=True)

ui.input_slider("marker_size", "Marker size", min=4, max=24, value=8)


@render_plotly
def plot():
    # The render function never reads marker_size, so this never re-runs:
    # zoom and selection survive every slider move.
    return px.scatter(df, x="gdpPercap", y="lifeExp", color="continent", log_x=True)


@reactive.effect
def _resize():
    with plot.widget.batch_update():
        for trace in plot.widget.data:
            trace.marker.size = input.marker_size()

Moving the slider resizes the markers without touching the zoom:

with plot.widget.batch_update(): sends many property changes as one update. Its sibling, plot.widget.batch_animate(duration=..., easing=...), tweens the changes smoothly – the gapminder app above animates its bubble chart this way, with no plotly frames.

Linking widgets

Put the two ideas together and one plot can drive another.

Highlight across plots

Lasso countries in the scatter plot, and their bars light up in a second figure. The bar chart is restyled in place, so its own state survives every selection.

import plotly.express as px
import plotly.graph_objects as go
from shiny import reactive
from shiny.express import ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)
top30 = df.nlargest(30, "pop").sort_values("pop")

ui.page_opts(title="Selection highlights a second plot", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly(listen_to=["selected_rows"])
        def scatter():
            fig = px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                custom_data=[df.index],
            )
            fig.update_layout(dragmode="lasso")
            return fig

    with ui.card(full_screen=True):

        @render_plotly
        def bars():
            fig = go.Figure(go.Bar(x=top30["pop"], y=top30["country"], orientation="h"))
            fig.update_traces(marker_color="lightgray")
            return fig


@reactive.effect
def _highlight():
    selected = set(scatter.selected_rows(df)["country"])
    colors = ["#1f77b4" if c in selected else "lightgray" for c in top30["country"]]
    bars.widget.data[0].marker.color = colors

linked highlight

Zoom to filter

relayout() reports the axis ranges after a zoom or pan – here, the bar chart recomputes its averages for just the countries in view. This one re-renders on purpose: the aggregate decides which bars exist, so there’s no fixed set of traces to restyle.

import plotly.express as px
from shiny.express import ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Zoom to filter a second view", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly
        def scatter():
            return px.scatter(df, x="lifeExp", y="gdpPercap", color="continent")

    with ui.card(full_screen=True):
        ui.card_header("Mean GDP/capita in the visible life-expectancy range")

        @render_plotly
        def summary_bar():
            axes = scatter.relayout() or {}
            if "xaxis.range[0]" in axes:
                lo, hi = axes["xaxis.range[0]"], axes["xaxis.range[1]"]
                visible = df[df["lifeExp"].between(lo, hi)]
            else:
                visible = df
            means = visible.groupby("continent", as_index=False)["gdpPercap"].mean()
            return px.bar(means, x="continent", y="gdpPercap")

Accessor reference

Accessor Returns Before any interaction Across a re-render Default rate policy
clicked() points DataFrame None kept none
hover() (opt-in) points DataFrame None kept debounce 250 ms
selected() (opt-in) points DataFrame None re-seeded none
selecting() (opt-in) points DataFrame None kept debounce 250 ms
brushed() region dict (range or lassoPoints) None re-seeded none
brushing() (opt-in) region dict None kept debounce 250 ms
relayout() axis-range dict None kept none
double_clicked() True (a pulse) None kept none
legend_clicked() traces DataFrame None kept none
visible_traces() traces DataFrame seeded from the figure re-seeded none
selected_rows(df, key=None) rows of df empty frame re-seeded (follows selected()) follows selected()

Opt-in accessors need the matching listen_to=[...] on @render_plotly. For selected_rows(), pass the name of the method you call: listen_to=["selected_rows"], or ["selected"] if you also call selected() directly.

clicked() and hover() frames have columns trace_index, point_index, x, y, and z/customdata when the figure has them. selected()/selecting() frames have only trace_index, point_index, and customdata – recover coordinates from your own data. point_index is a position within a trace, not a row of your data: with color=, each color group is its own trace, so match rows through customdata.

hover()

Same columns as clicked(), reported as the mouse moves over points and cleared to None when it leaves them. It updates once the mouse settles, not on every pixel. A detail card that previews a point without a click:

import plotly.express as px
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Hover for details", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_plotly(listen_to=["hover"])
        def plot():
            return px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                size="pop",
                size_max=40,
                custom_data=[df.index],
            )

    with ui.card():

        @render.ui
        def detail():
            pts = plot.hover()
            if pts is None:
                return ui.p("Hover a bubble for details.", class_="text-muted")
            row = df.loc[pts["customdata"].iloc[0][0]]
            return ui.TagList(
                ui.h4(row["country"]),
                ui.p(f"Continent: {row['continent']}"),
                ui.p(f"Life expectancy: {row['lifeExp']:.1f} years"),
                ui.p(f"GDP per capita: ${row['gdpPercap']:,.0f}"),
            )

relayout()

Reports the axis ranges after a zoom, pan, or autoscale, and nothing else – it stays quiet through renders, modebar clicks, and selections.

import plotly.express as px
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)


def fmt(v: object) -> str:
    return f"{v:.1f}" if isinstance(v, float) else str(v)


ui.page_opts(title="Zoom in", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly
        def plot():
            return px.scatter(df, x="lifeExp", y="gdpPercap", color="continent")

    with ui.card():
        ui.card_header("plot.relayout()")

        @render.code
        def relayout_out():
            axes = plot.relayout()
            if axes is None:
                return "None (zoom or pan)"
            return "\n".join(f"{k}: {fmt(v)}" for k, v in axes.items())

relayout after zoom

A double-click reset reports {"xaxis.autorange": True, "yaxis.autorange": True} rather than numbers: treat it as “back to the full extent”. On a log axis, ranges are log10 of the data (2.8 for a gdpPercap of about 630), so apply 10 ** value before filtering data with them. Each report holds only the keys the gesture changed; for the figure’s complete current ranges, read plot.widget.layout.

legend_clicked() and visible_traces()

legend_clicked() reports the trace(s) the last legend click affected: the clicked trace first, then its legendgroup mates if the whole group toggled. visible_traces() reports what’s on screen right now – every trace and whether it’s visible, kept current through legend clicks, double-click-to-isolate, and your own .widget changes. Reach for visible_traces() rather than replaying legend clicks yourself:

import plotly.express as px
from shiny import req
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Toggle legend items to filter the summary", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_plotly
        def plot():
            return px.scatter(df, x="gdpPercap", y="lifeExp", color="continent", log_x=True)

    with ui.card():
        ui.card_header("Mean life expectancy, visible continents only")

        @render.data_frame
        def summary():
            vis = plot.visible_traces()
            # None until the browser reports the seed just after first draw
            req(vis is not None)
            shown = set(vis.loc[vis["visible"], "name"])
            subset = df[df["continent"].isin(shown)]
            agg = subset.groupby("continent", as_index=False)["lifeExp"].mean().round(1)
            return render.DataGrid(agg)

        "plot.legend_clicked() -- the trace(s) the last click affected"

        @render.code
        def last_click():
            traces = plot.legend_clicked()
            if traces is None:
                return "None (click a legend item)"
            return ";".join(f"{r.trace_index},{r.name}" for r in traces.itertuples())

Click “Africa” in the legend to hide it: legend_clicked() reports 2,Africa (its trace index and name) and the summary table drops that row:

selected() and selecting()

selected() reports the selected points once, when the drag ends; selecting() streams them while the user is still dragging. Both are opt-in:

import plotly.express as px
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Box-select some bubbles", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly(listen_to=["selected", "selecting"])
        def plot():
            fig = px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                custom_data=[df.index],
            )
            fig.update_layout(dragmode="select")
            return fig

    with ui.card():
        "plot.selecting() -- while dragging"

        @render.code
        def selecting_out():
            pts = plot.selecting()
            return "None" if pts is None else f"{len(pts)} points"

        "plot.selected() -- once the drag ends"

        @render.code
        def selected_out():
            pts = plot.selected()
            if pts is None or pts.empty:
                return "None (drag a box)"
            # Selection frames are slim (no x/y): the coordinates live in
            # your own data -- here customdata carries the df.index labels.
            rows = df.loc[[cd[0] for cd in pts["customdata"]]]
            return rows[["country", "lifeExp", "gdpPercap"]].round(1).to_string(index=False)

Mid-drag, selecting() already has points but selected() hasn’t fired yet:

brushed() and brushing()

Where selected() reports points, brushed() reports the region the user drew – a box as {"range": {"x": [...], "y": [...]}}, a lasso as {"lassoPoints": {"x": [...], "y": [...]}} – in data units, even on a log axis. Use it when you need the shape itself, e.g. to draw it on another plot or test your own points against it. brushing() streams the region mid-drag.

import plotly.express as px
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Lasso some bubbles", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly(listen_to=["brushing"])
        def plot():
            fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent", log_x=True)
            fig.update_layout(dragmode="lasso")
            return fig

    with ui.card():
        "plot.brushing() -- while dragging"

        @render.code
        def brushing_out():
            region = plot.brushing()
            return "None" if region is None else list(region.keys())[0]

        "plot.brushed() -- once the drag ends"

        @render.code
        def brushed_out():
            region = plot.brushed()
            if region is None:
                return "None (drag a lasso)"
            shape, coords = next(iter(region.items()))
            rounded = {axis: [round(v, 1) for v in vs] for axis, vs in coords.items()}
            return f"{shape}: {rounded}"

brushed after a lasso

double_clicked()

A pulse rather than a value: None until the first double-click, then True, re-firing its readers on every later double-click. Use it when a different widget needs to react to “the user reset the view”:

import plotly.express as px
import plotly.graph_objects as go
from shiny import reactive, req
from shiny.express import ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)
top15 = df.nlargest(15, "pop").sort_values("pop")

ui.page_opts(title="Click a bubble, double-click to reset", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly
        def scatter():
            return px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                custom_data=[df.index],
            )

    with ui.card(full_screen=True):

        @render_plotly
        def bars():
            fig = go.Figure(go.Bar(x=top15["pop"], y=top15["country"], orientation="h"))
            fig.update_traces(marker_color="lightgray")
            return fig


@reactive.effect
def _highlight():
    pts = scatter.clicked()
    req(pts is not None)
    country = df.loc[pts["customdata"].iloc[0][0], "country"]
    with bars.widget.batch_update():
        for trace in bars.widget.data:
            trace.marker.color = [
                "#1f77b4" if c == country else "lightgray" for c in top15["country"]
            ]


# clicked() already clears itself on a background double-click, but that only
# resets scatter's own reader. double_clicked() is the general "the user
# reset the view" pulse -- reach for it when a *different* widget needs to
# react to a reset, including on subplot types (mapbox, ternary) where
# relayout()'s axis-range filter never reports one.
@reactive.effect
def _reset_bars():
    req(scatter.double_clicked())
    with reactive.isolate(), bars.widget.batch_update():
        for trace in bars.widget.data:
            trace.marker.color = "lightgray"

Click a bubble to highlight its bar, then double-click the background to reset it:

It fires on cartesian, map (scattermap/mapbox), and ternary charts, but not on 3D scenes, where plotly doesn’t report a double-click at all.

How double-clicks and clicks interact with the other accessors:

  • A double-click on empty background clears clicked(). Double-clicking a point leaves it showing that point.
  • A double-click after a box or lasso selection clears selected(), selecting(), brushed(), and brushing(). In select or lasso drag mode, that deselect doesn’t pulse double_clicked().
  • In select or lasso drag mode, a plain click also counts as an (empty) selection, so it clears selected() and brushed(). Clicking and lassoing on the same figure interact.

Polars and key=

Without key, selected_rows() matches custom_data=[df.index] against df.index, so it’s safe even if df was filtered or sorted after the figure was built. With any data frame – including polars, which has no index – put an id column in custom_data and name it as the key:

import plotly.express as px
import polars as pl
from shiny.express import render, ui
from shinywidgets import render_plotly

pdf = px.data.gapminder().query("year == 2007")
df = pl.from_pandas(pdf[["country", "continent", "gdpPercap", "lifeExp"]])

ui.page_opts(title="Lasso-select countries (polars)", fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_plotly(listen_to=["selected_rows"])
        def plot():
            fig = px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                custom_data=["country"],
            )
            fig.update_layout(dragmode="lasso")
            return fig

    with ui.card(full_screen=True):
        ui.card_header("plot.selected_rows(df, key='country')")

        @render.data_frame
        def rows():
            rows = plot.selected_rows(df, key="country")
            rows = rows.with_columns(pl.col("gdpPercap", "lifeExp").round(1))
            return render.DataGrid(rows.to_pandas())

selected_rows, polars

Without custom_data on the figure, selected_rows() raises an error that says what to add.

Across re-renders

A re-render gives the user a new figure. Most accessors keep their last value until the user interacts with the new one, so a reader may briefly see a click from the previous figure. If the data changed, a kept point_index can point at a different point; match on customdata instead, as selected_rows() does. selected(), brushed(), and visible_traces() are the exception: they describe the figure’s current state, so they reset to what the new figure shows (nothing selected).

Tuning accessors

Reading on demand

An accessor records from the moment the figure renders, whether or not anything has read it yet. So you can leave one unread until a button click, a download handler, or an LLM tool call needs it – the lasso the user made earlier isn’t lost:

import plotly.express as px
from shiny.express import input, render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Lasso now, read later", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_plotly(listen_to=["selected_rows"])
        def plot():
            fig = px.scatter(
                df,
                x="gdpPercap",
                y="lifeExp",
                color="continent",
                log_x=True,
                custom_data=[df.index],
            )
            fig.update_layout(dragmode="lasso")
            return fig

    with ui.card():
        "Lasso some bubbles. Nothing reads the selection until you click Export."
        ui.input_action_button("export", "Export selection")

        @render.code
        def summary():
            if input.export() == 0:
                return "Nothing read yet."
            rows = plot.selected_rows(df)
            if rows.empty:
                return "No selection to export."
            return (
                f"{len(rows)} countries\n"
                f"mean life expectancy {rows['lifeExp'].mean():.1f} years"
            )

Rate limiting

hover(), selecting(), and brushing() are debounced by 250 ms by default, since they can fire many times a second. The other accessors fire at most once per gesture. Pass rate_delay=0 to @render_plotly to see every event – for debugging, or for a cheap computation where the debounce’s lag is more noticeable than its benefit:

import plotly.express as px
from shiny import reactive
from shiny.express import render, ui
from shinywidgets import render_plotly

df = px.data.gapminder().query("year == 2007").reset_index(drop=True)

ui.page_opts(title="Debounced vs. unlimited selecting()", fillable=True)

count_debounced = reactive.value(0)
count_live = reactive.value(0)

with ui.layout_columns():
    with ui.card(full_screen=True):
        "Default: debounced 250ms"

        @render_plotly(listen_to=["selecting"])
        def debounced():
            fig = px.scatter(df, x="gdpPercap", y="lifeExp", log_x=True)
            fig.update_layout(dragmode="select")
            return fig

        @reactive.effect
        def _count_debounced():
            debounced.selecting()
            with reactive.isolate():
                count_debounced.set(count_debounced() + 1)

        @render.text
        def n_debounced():
            return f"selecting() fired {count_debounced()} times"

    with ui.card(full_screen=True):
        "rate_delay=0: fires on every drag event"

        @render_plotly(listen_to=["selecting"], rate_delay=0)
        def live():
            fig = px.scatter(df, x="gdpPercap", y="lifeExp", log_x=True)
            fig.update_layout(dragmode="select")
            return fig

        @reactive.effect
        def _count_live():
            live.selecting()
            with reactive.isolate():
                count_live.set(count_live() + 1)

        @render.text
        def n_live():
            return f"selecting() fired {count_live()} times"

The same slow drag, debounced vs. with rate_delay=0:

rate limiting comparison

.read()

plot.read("selected") reads an accessor by name, the same value as plot.selected(); it’s meant for code that handles outputs generically. For plotly, the accessors are the whole interaction surface – there are no other widget traits worth reading reactively.

Large data

go.Scattergl/render_mode="webgl" draws points on the GPU instead of SVG; above about 10,000 points, swap go.Scatter/px.scatter for it. Return (figure, config) from the render function to pass Plotly.js config options (here, hiding the modebar) the same way Dash’s dcc.Graph(figure=, config=) does – this is the “draw it with the GPU in the browser” approach from Large data & performance:

import numpy as np
import plotly.graph_objects as go
from shiny.express import ui
from shinywidgets import render_plotly

rng = np.random.default_rng(0)
n = 200_000
x = rng.normal(size=n)
y = x * 0.6 + rng.normal(size=n)

ui.page_opts(title="200k points", fillable=True)


@render_plotly
def big_scatter():
    fig = go.Figure(
        go.Scattergl(x=x, y=y, mode="markers", marker=dict(size=3, opacity=0.3))
    )
    return fig, {"displayModeBar": False}

large data, no modebar

Numeric arrays travel to the browser as binary arrays, so a float32 array (x.astype("float32")) roughly halves the payload for very large traces.

At millions of rows, lassoing raw points stops scaling: the payload and server-side work grow with the selection. Linking widgets: brushing large data shows how to push summaries instead (a datashader raster, a Mosaic crossfilter).

Layout and sizing

A figure fills its output by default, with plotly’s wide default margins trimmed, and resizes with its container (full-screen cards, sidebar collapse). Giving the figure its own layout.height, or passing @render_plotly(height="300px"), renders it at that fixed height instead:

import plotly.express as px
from shiny.express import ui
from shinywidgets import render_plotly

df = px.data.iris()

ui.page_opts(title="Sizing", fillable=True)

with ui.card(full_screen=True):
    "Fills its card (no explicit height) -- try full_screen"

    @render_plotly
    def fills():
        return px.scatter(df, x="sepal_width", y="sepal_length", color="species")


with ui.card():
    "Fixed height: an explicit height= sizes the plot directly"

    @render_plotly(height="300px")
    def fixed():
        return px.scatter(df, x="sepal_width", y="sepal_length", color="species")

layout and sizing

Gotchas

  • .value is not the live figure. When the render function returns a go.Figure, .value is exactly that object; @render_plotly coerces a copy into .widget. Mutating .value after returning it does nothing visible – always mutate .widget.
  • Plotly.py’s own trace callbacks only fire if registered inside the render function. @render_plotly mutes plotly.py’s per-point event reports unless the figure it renders already has an on_click(), on_hover(), on_unhover(), on_selection(), or on_deselect() callback. A callback registered later (e.g. on .widget from a reactive.effect) silently never fires, and .widget.data[i].selectedpoints never updates. Prefer the accessors above; otherwise register callbacks before returning the figure, or turn native events on app-wide with shinywidgets.config(native_events=True).

Learn more