plotnine

Pan, zoom, and click into any ggplot, and render plot compositions that Shiny’s static render.plot can’t show at all.

plotnine brings R’s ggplot2 grammar of graphics to Python: layered geoms, scales, facets, and themes, composable with +. @render_plotnine renders a ggplot – or a composition of several, laid out with | and / – as a live ipympl widget, with a zoom/pan toolbar and a clicked()/limits() accessor pair, all without leaving Python.

hero

A scatter plot, a box plot, and a histogram, composed into one figure with | and /. Try the app.

Installation

pip install 'shinywidgets[plotnine]'

This installs plotnine and ipympl, the live-canvas backend render_plotnine draws to.

Quick start

from plotnine import aes, geom_point, geom_smooth, ggplot, labs, theme_minimal
from plotnine.data import mpg
from shiny.express import ui
from shinywidgets import render_plotnine

ui.page_opts(title="plotnine quick start", fillable=True)

with ui.card(full_screen=True):
    ui.card_header("Engine displacement vs. highway MPG")

    @render_plotnine
    def plot():
        return (
            ggplot(mpg, aes("displ", "hwy", color="class"))
            + geom_point(size=2.5, alpha=0.8)
            + geom_smooth(method="lm", color="black", se=False)
            + labs(x="Displacement (L)", y="Highway MPG", color="Class")
            + theme_minimal()
        )

quickstart

Return a ggplot from the decorated function, the same as from a notebook cell – render_plotnine draws a copy (your own plot object is never mutated) and resizes the figure to fill the card, re-running plotnine’s own layout engine (legend, axis labels, facet strips) on every resize. Hover the plot and a toolbar fades in with zoom, pan, home/back/forward, and PNG download.

Overview

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

Plot compositions

plotnine arranges whole plots next to and above one another with | and / – the same operators patchwork popularized in R. render_plotnine treats the result as a single widget: one toolbar, one resize target, re-laid out as a unit.

from plotnine import aes, geom_boxplot, geom_histogram, geom_point, ggplot, labs, theme
from plotnine.data import penguins
from shiny.express import ui
from shinywidgets import render_plotnine

penguins = penguins.dropna().reset_index(drop=True)

ui.page_opts(title="plotnine compositions", fillable=True)

no_legend = theme(legend_position="none")

with ui.card(full_screen=True):
    ui.card_header("Bill shape, species, and flipper length")

    @render_plotnine
    def composed():
        scatter = (
            ggplot(penguins, aes("bill_length_mm", "bill_depth_mm", color="species"))
            + geom_point()
            + labs(x="Bill length (mm)", y="Bill depth (mm)", color="Species")
        )
        box = (
            ggplot(penguins, aes("species", "body_mass_g", fill="species"))
            + geom_boxplot()
            + labs(x="", y="Body mass (g)")
            + no_legend
        )
        hist = (
            ggplot(penguins, aes("flipper_length_mm", fill="species"))
            + geom_histogram(bins=30, alpha=0.7, position="identity")
            + labs(x="Flipper length (mm)", y="Count")
            + no_legend
        )
        return (scatter | box) / hist

compositions

(scatter | box) / hist lays the three plots out as one figure – a scatter and a box plot side by side, a histogram underneath. @render.plot can’t display this at all: it raises a TypeError naming the composition’s exact type, since it only knows how to draw a single plot. This is the most direct reason to reach for render_plotnine over the static renderer when a dashboard panel needs more than one related plot.

Reacting to interaction

The output gains methods, called accessors, that read what the user does to the figure, much like input.my_slider() reads an input. Call one from any reactive context (a @render.* function, @reactive.calc, or @reactive.effect), and that context re-runs whenever the value changes. These are the same underlying accessors as render_matplotlib – both renderers coerce to the same ipympl Canvas – but here the coordinates are plotnine’s own transformed space, not necessarily the values in your data frame.

Click: the nearest point

import numpy as np
from plotnine import aes, geom_point, ggplot, labs, theme_minimal
from plotnine.data import mpg
from shiny import reactive, req
from shiny.express import render, ui
from shinywidgets import render_plotnine

ui.page_opts(title="plot.clicked(): nearest point", fillable=True)
nearest = reactive.value(None)

with ui.layout_columns():
    with ui.card(full_screen=True):

        @render_plotnine
        def plot():
            return (
                ggplot(mpg, aes("displ", "hwy"))
                + geom_point(size=2.5, alpha=0.7)
                + labs(x="Displacement (L)", y="Highway MPG")
                + theme_minimal()
            )

    with ui.card():
        ui.card_header("Clicked car")

        @render.ui
        def detail():
            # Compare to None explicitly: a row position of 0 is falsy, so
            # req(nearest()) would wrongly treat that valid click as "no click"
            i = nearest()
            if i is None:
                return ui.p("Click a point to see that car here.")
            row = mpg.iloc[i]
            return ui.p(
                f"{row.manufacturer.title()} {row.model}: {row.displ} L, {row.hwy} MPG hwy"
            )


@reactive.effect
def _mark_nearest():
    event = plot.clicked()
    canvas = plot.widget
    req(event, canvas)
    ax = canvas.figure.axes[0]
    xy = ax.transData.transform(mpg[["displ", "hwy"]].to_numpy())
    i = int(np.hypot(xy[:, 0] - event.x, xy[:, 1] - event.y).argmin())
    nearest.set(i)

    for artist in list(ax.lines):
        if artist.get_label() == "_clicked":
            artist.remove()
    row = mpg.iloc[i]
    ax.plot(
        [row.displ],
        [row.hwy],
        "o",
        ms=14,
        mfc="none",
        mec="black",
        mew=2,
        label="_clicked",
    )
    canvas.draw_idle()

clicked() gives you a raw MouseEvent, not a row – plotnine keeps no mapping from pixels back to your data frame. The recipe: transform your data’s x/y columns to display (pixel) coordinates with ax.transData.transform(...), then compare against event.x/event.y (also in display coordinates) with a plain nearest-neighbor search. Comparing in display space, rather than data space, avoids unit mismatches when x and y have very different scales. The effect reads both plot.clicked() (so it re-runs on each press) and plot.widget (the current canvas), so it can draw a circle around the match directly on the figure, keeping the circle and the user’s zoom level both visible at once.

Zoom is a reactive value

import matplotlib.dates as mdates
from plotnine import aes, geom_line, ggplot, labs, theme_minimal
from plotnine.data import economics
from shiny.express import render, ui
from shinywidgets import render_plotnine

ui.page_opts(title="plot.limits(): zoom is a query", fillable=True)

with ui.layout_columns():
    with ui.card(full_screen=True):

        @render_plotnine
        def plot():
            return (
                ggplot(economics, aes("date", "unemploy"))
                + geom_line()
                + labs(x="", y="Unemployed (thousands)")
                + theme_minimal()
            )

    with ui.card():
        ui.card_header("Visible window")

        @render.text
        def window():
            (x0, x1), _ = plot.limits()
            # x0/x1 are plotnine's *transformed* x values -- here matplotlib's
            # date-number epoch, not a datetime -- convert to read them
            lo, hi = mdates.num2date(x0), mdates.num2date(x1)
            return f"{lo:%b %Y} to {hi:%b %Y}"

limits(ax=0) is seeded from the figure’s rendered limits, then updates (debounced 250 ms) after every zoom or pan step. The values are in plotnine’s transformed coordinate space – here matplotlib’s date-number epoch, so reading them as a date needs matplotlib.dates.num2date(), the same way clicked()’s .xdata would need 10 ** x to recover a value under scale_x_log10(). It can’t be read inside the plot’s own render function, which builds a new figure every run – read it in another output or an effect instead.

Updating in place

Two ways to change a plot that’s already on screen:

  • Re-render (return a new ggplot from the decorated function): simplest, and the only option when the underlying data actually changes shape. plotnine draws an entirely new figure, so the user’s zoom, pan position, and any artists you added (like the circle marker above) are all lost.
  • Update in place, from a @reactive.effect that reads .widget and edits the matplotlib Axes directly (ax.lines[i].set_ydata(...), add an artist, etc.), then calls canvas.draw_idle(): the figure keeps its current zoom and pan, and nothing is re-sent except the one redrawn frame.

A ggplot object isn’t mutable the way a plotly FigureWidget or a bokeh ColumnDataSource is, so an in-place update means reaching past plotnine into the matplotlib artists it produced – the same technique render_matplotlib documents. Which artist is “the line” depends on your geoms and draw order (ax.lines[0] for a single geom_line, ax.collections[0] for a single geom_point), and that index isn’t guaranteed stable if you add or remove layers – inspect ax.lines/ax.collections once on a drawn figure to find the index you need.

import numpy as np
import pandas as pd
from plotnine import aes, geom_line, ggplot, scale_y_continuous, theme_minimal
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_plotnine

ui.page_opts(title="Re-render vs. in-place", fillable=True)
ui.input_slider("freq", "Frequency", 1, 10, 3)

x = np.linspace(0, 1, 400)


def wave(freq: int) -> pd.DataFrame:
    return pd.DataFrame({"x": x, "y": np.sin(2 * np.pi * freq * x)})


with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("Re-render: zoom resets")

        @render_plotnine
        def rerendered():
            return (
                ggplot(wave(input.freq()), aes("x", "y"))
                + geom_line()
                + scale_y_continuous(limits=(-1.1, 1.1))
                + theme_minimal()
            )

    with ui.card(full_screen=True):
        ui.card_header("In-place: zoom survives")

        @render_plotnine
        def inplace():
            # Doesn't read input.freq(): built once, edited afterward
            return (
                ggplot(wave(3), aes("x", "y"))
                + geom_line()
                + scale_y_continuous(limits=(-1.1, 1.1))
                + theme_minimal()
            )


@reactive.effect
def _update_wave():
    freq = input.freq()
    with reactive.isolate():
        canvas = inplace.widget
    if canvas is None:
        return
    line = canvas.figure.axes[0].lines[0]
    line.set_ydata(np.sin(2 * np.pi * freq * x))
    canvas.draw_idle()

Both plots zoomed to the same window, then the frequency slider moved to 8:

The re-rendered plot (left) snapped back to showing the full x-axis and lost the zoom; the in-place plot (right) kept exactly the same window while the waveform inside it changed. reactive.isolate() around reading inplace.widget keeps the effect from creating a dependency on the render itself – it only needs to run when input.freq() changes, not every time the (here, never re-rendered) widget changes.

Linking widgets

Zoom drives a second plot

import matplotlib.dates as mdates
import pandas as pd
from plotnine import aes, geom_line, ggplot, labs, theme_minimal
from plotnine.data import economics
from shiny.express import render, ui
from shinywidgets import render_plotnine

ui.page_opts(title="Zoom drives a linked plot", fillable=True)


def visible_window():
    (x0, x1), _ = top.limits()
    lo = pd.Timestamp(mdates.num2date(x0).replace(tzinfo=None))
    hi = pd.Timestamp(mdates.num2date(x1).replace(tzinfo=None))
    return economics[(economics.date >= lo) & (economics.date <= hi)]


with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("Unemployment -- zoom into a stretch")

        @render_plotnine
        def top():
            return (
                ggplot(economics, aes("date", "unemploy"))
                + geom_line()
                + labs(x="", y="Unemployed (thousands)")
                + theme_minimal()
            )

    with ui.card(full_screen=True):
        ui.card_header("Savings rate, same window")

        @render_plotnine
        def bottom():
            return (
                ggplot(visible_window(), aes("date", "psavert"))
                + geom_line(color="darkorange")
                + labs(x="", y="Personal savings rate (%)")
                + theme_minimal()
            )


with ui.card():
    ui.card_header("Summary of the visible window")

    @render.text
    def summary():
        visible = visible_window()
        return f"{len(visible)} months visible, average unemployment {visible.unemploy.mean():,.0f}k"

The bottom plot and the summary text both call top.limits() directly – no reactive.value, no ax.callbacks.connect, no separate tracking effect: Shiny’s normal reactive graph (bottom/summary depend on top.limits(), which depends on the user’s zoom) handles the rest. The two series have unrelated y-scales (thousands of people vs. a percentage), which is exactly when a second plot, not a shared axis, is the right way to link them – plotnine facets share one scale per row/column, which wouldn’t work here.

Accessor reference

accessor returns before any interaction across re-render default rate policy
clicked() matplotlib.backend_bases.MouseEvent None kept not rate-limited
limits(ax=0) ((x0, x1), (y0, y1)) for panel ax seeded value (the figure’s rendered limits) re-seeded debounced, 250 ms

render_matplotlib also has picked(); plotnine doesn’t get it. plotnine’s geoms reject matplotlib’s picker= kwarg outright, so no plotnine artist can ever be made pickable – picked() would just never fire.

Find the clicked facet

event.inaxes names which Axes a press landed on, but not its facet value – facets are just a grid of ordinary matplotlib axes to the event system. plotnine’s own drawn layout maps panel number to facet value, in the same order as figure.axes:

import numpy as np
from plotnine import aes, facet_wrap, geom_point, ggplot, labs, theme_minimal
from plotnine.data import mpg
from shiny import reactive, req
from shiny.express import render, ui
from shinywidgets import render_plotnine

ui.page_opts(title="Click a facet, know the panel", fillable=True)
found = reactive.value(None)

with ui.layout_columns():
    with ui.card(full_screen=True):

        @render_plotnine
        def plot():
            return (
                ggplot(mpg, aes("displ", "hwy"))
                + geom_point(size=2, alpha=0.7)
                + facet_wrap("~drv", labeller="label_both")
                + labs(x="Displacement (L)", y="Highway MPG")
                + theme_minimal()
            )

    with ui.card():
        ui.card_header("Clicked panel")

        @render.ui
        def detail():
            drv, row = req(found())
            return ui.p(
                f"drv = {drv}: {row.manufacturer.title()} {row.model} "
                f"({row.displ} L, {row.hwy} MPG)"
            )


@reactive.effect
def _locate_click():
    event = plot.clicked()
    canvas = plot.widget
    req(event, canvas)
    # Facets are separate matplotlib axes; plotnine's own layout table (built
    # while drawing) says which facet value each one holds, in `figure.axes`
    # order.
    panel = canvas.figure.get_layout_engine().plot.facet.layout.layout
    i = canvas.figure.axes.index(event.inaxes)
    drv = panel["drv"].iloc[i]

    subset = mpg[mpg["drv"] == drv].reset_index(drop=True)
    xy = event.inaxes.transData.transform(subset[["displ", "hwy"]].to_numpy())
    j = int(np.hypot(xy[:, 0] - event.x, xy[:, 1] - event.y).argmin())
    found.set((drv, subset.iloc[j]))

figure.get_layout_engine().plot is the ggplot plotnine attached to the figure, and its .facet.layout.layout is a data frame that assigns each facet a panel number in the same order as figure.axes. figure.axes.index(event.inaxes) gives you the row into that table, and from there the facet’s data value (here, drv). This relies on an attribute path plotnine doesn’t guarantee as public API.

limits(ax) across facet panels

ax indexes panels: with facet_wrap()/facet_grid(), limits(ax=1) reads the second facet panel’s own x/y range, in the same order as .widget.figure.axes.

from plotnine import aes, facet_wrap, geom_point, ggplot, labs, theme_minimal
from plotnine.data import mpg
from shiny.express import render, ui
from shinywidgets import render_plotnine

ui.page_opts(title="plot.limits(ax): which facet panel?", fillable=True)

with ui.layout_columns():
    with ui.card(full_screen=True):

        @render_plotnine
        def plot():
            return (
                ggplot(mpg, aes("displ", "hwy"))
                + geom_point(size=2, alpha=0.7)
                + facet_wrap("~drv", labeller="label_both")
                + labs(x="Displacement (L)", y="Highway MPG")
                + theme_minimal()
            )

    with ui.card():
        ui.card_header("Per-panel x ranges")

        @render.code
        def ranges():
            n = len(plot.widget.figure.axes)
            lines = []
            for i in range(n):
                x0, x1 = plot.limits(ax=i)[0]
                lines.append(f"ax={i}: {x0:.2f} to {x1:.2f}")
            return "\n".join(lines)

Zooming a single facet panel only changes that panel’s own entry – the other two stay at the full range, confirming ax tracks panels independently and in figure.axes order.

Across a re-render

clicked() attaches the moment the figure renders and keeps its value across a re-render – the payload then describes the previous render’s figure, so prefer an ID-keyed lookup over a positional row index if your data can change shape between renders. limits() instead re-seeds from the new figure’s own view on every render, since it describes the figure’s current state rather than something the user did.

Tuning accessors

Reading on demand

Because every accessor is live from the moment the figure renders, it’s safe to read one anywhere – a button handler, a download handler, a @reactive.event – not just from an output that’s always on screen. Here, a “Save current view” button reads plot.limits() on click and appends it to a running list, with no warm-up @reactive.effect needed to make the first read work:

from plotnine import aes, geom_point, ggplot, labs, theme_minimal
from plotnine.data import mpg
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_plotnine

ui.page_opts(title="Save the current zoom window", fillable=True)
ui.input_action_button("save", "Save current view")

bookmarks = reactive.value([])


@render_plotnine
def plot():
    return (
        ggplot(mpg, aes("displ", "hwy", color="class"))
        + geom_point(size=2.5, alpha=0.8)
        + labs(x="Displacement (L)", y="Highway MPG", color="Class")
        + theme_minimal()
    )


@reactive.effect
@reactive.event(input.save)
def _save_view():
    (x0, x1), (y0, y1) = plot.limits()
    bookmarks.set([*bookmarks(), f"x: {x0:.1f}-{x1:.1f}, y: {y0:.1f}-{y1:.1f}"])


@render.code
def saved():
    views = bookmarks()
    if not views:
        return "No views saved yet -- zoom in, then click Save."
    return "\n".join(f"{i + 1}. {v}" for i, v in enumerate(views))

read on demand

Clicking Save before any zoom records the figure’s full extent (limits() is already seeded, not None); zooming in and clicking Save again appends the new window.

Rate limiting

clicked() has no default rate policy: it reports every press immediately, because a click is a discrete event, not a stream. limits() is debounced 250 ms by default – a zoom-to-rectangle drag fires many xlim_changed events, and only the settled value after the pause reaches Python. Pass rate_delay=0 to react to every event instead (e.g. to drive a second plot smoothly while panning), or rate_policy="throttle" to get evenly-spaced updates during a long drag rather than waiting for it to stop:

from plotnine import aes, geom_line, ggplot, labs, theme_minimal
from plotnine.data import economics
from shiny.express import render, ui
from shinywidgets import render_plotnine

ui.page_opts(fillable=True)

counts = {"default": 0, "fast": 0}


def make_plot():
    return (
        ggplot(economics, aes("date", "unemploy"))
        + geom_line()
        + labs(x="", y="Unemployed (thousands)")
        + theme_minimal()
    )


with ui.layout_columns():
    with ui.card():
        ui.card_header("default: debounced 250ms")

        @render_plotnine
        def default_out():
            return make_plot()

        @render.code
        def default_count():
            default_out.limits()
            counts["default"] += 1
            return f"limits() recomputed {counts['default']} times"

    with ui.card():
        ui.card_header("rate_delay=0: every event")

        @render_plotnine(rate_delay=0)
        def fast_out():
            return make_plot()

        @render.code
        def fast_count():
            fast_out.limits()
            counts["fast"] += 1
            return f"limits() recomputed {counts['fast']} times"

rate limiting

Panning the same distance on both plots: the debounced plot recomputes once the drag settles, while the rate_delay=0 plot recomputes continuously, once per intermediate event along the drag.

.read() and reactive_read()

plotnine’s canvas has no synced trait worth reading reactively beyond the two accessors above – use limits() for the current view rather than trying to read it another way.

Large data

plotnine shares matplotlib’s ipympl engine and has no large-data mode of its own: no WebGL, no server-side rasterization, and every pan/zoom redraws the whole figure to a bitmap. Reach for bokeh, plotly, or datashader when the data itself needs to scale into the millions – see Large data & performance for how those approaches compare.

Layout and sizing

from plotnine import aes, geom_point, ggplot, theme, theme_minimal
from plotnine.data import mpg
from shiny.express import ui
from shinywidgets import render_plotnine

ui.page_opts(fillable=True)


def scatter():
    return ggplot(mpg, aes("displ", "hwy")) + geom_point() + theme_minimal()


with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("Fills its card (default)")

        @render_plotnine
        def fills():
            return scatter()

    with ui.card():
        ui.card_header("Explicit height: set a matching figure_size")

        @render_plotnine(height="220px")
        def fixed():
            return scatter() + theme(figure_size=(4, 2.2))

layout sizing comparison

In a filling layout (the default: no height given), render_plotnine resizes the figure to its container on every render and resize, overriding any theme(figure_size=...) you set – that’s the left card above. Give the output an explicit height and the figure is drawn at its figure_size and not fitted to the output: a bigger figure than the output is clipped, so set a matching theme(figure_size=...) yourself, as the right card does. With fill=False and no height, the figure’s width still tracks its container; only the height becomes fixed. Leave theme(dpi=...) at its default (100) in either case – a higher DPI acts like a zoom factor on top of the CSS size rather than a HiDPI setting (HiDPI scaling is automatic).

render_plotnine hides the canvas chrome for you: canvas.header_visible = False (the “Figure N” label is meaningless once plotnine closes its pyplot figure after drawing) and canvas.footer_visible = False (the cursor-coordinate readout shows plotnine’s transformed units, e.g. scientific notation under a log scale, which is more confusing than useful).

Facets relayout live on resize

Every resize – dragging the window, collapsing a sidebar, entering full_screen – triggers a real plotnine redraw, not a CSS rescale. Facet strips, legend placement, and axis label wrapping are recomputed at the new size, the same as they would be if you called .draw() again at a different figure_size:

from plotnine import aes, facet_wrap, geom_point, ggplot, labs, theme_light
from plotnine.data import mpg
from shiny.express import ui
from shinywidgets import render_plotnine

ui.page_opts(title="Facets that relayout live", fillable=True)

with ui.card(full_screen=True):
    ui.card_header("Highway MPG by displacement, faceted by drivetrain")

    @render_plotnine
    def plot():
        return (
            ggplot(mpg, aes("displ", "hwy", color="class"))
            + geom_point(size=2)
            + facet_wrap("~drv", labeller="label_both")
            + labs(x="Displacement (L)", y="Highway MPG", color="Class")
            + theme_light()
        )

This is what theme(dpi=...) and theme(figure_size=...) would otherwise need you to pick in advance for a static image.

Gotchas

  • Zooming in close enough can leave an axis with no tick labels at all, since plotnine computes its axis breaks once, when it draws. Fix it in an effect that reads .widget, after the render:

    import matplotlib.dates as mdates
    loc = mdates.AutoDateLocator()
    ax.xaxis.set_major_locator(loc)
    ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))

    For a numeric (non-date) axis, use matplotlib.ticker.MaxNLocator and ScalarFormatter the same way.

  • clicked()/limits() coordinates are in plotnine’s transformed space, not necessarily your data’s units. Under scale_x_log10(), values are log10(x); dates are matplotlib’s own num2date epoch; discrete scales use integer positions 1..n in their displayed order. Convert before comparing against your own data.

Learn more