PyVista

Turn a pyvista Plotter into an interactive, client-side 3D view – rotate, zoom, pan, no server round-trips.

PyVista is a Pythonic front end for VTK: meshes, volumes, and point clouds that would take pages of raw VTK code become a few lines of pv.Plotter() calls. @render_pyvista renders the Plotter your function builds as an interactive 3D view – drag to rotate, scroll to zoom – but none of that interaction reaches Python: there’s no accessor, and nothing to reactive_read(). Instead, drive the Plotter itself from ordinary Shiny inputs (a threshold, a clip plane, a colormap), and pair the re-rendered view with statistics computed from the same mesh in Python.

hero

A synthetic rolling-hills terrain colored by its elevation field. Try the app.

Installation

pip install 'shinywidgets[pyvista]'

This installs PyVista’s jupyter extra, which @render_pyvista needs.

Quick start

import pyvista as pv
from shiny.express import ui
from shinywidgets import render_pyvista

pv.OFF_SCREEN = True  # required on a headless server

ui.page_opts(fillable=True)


@render_pyvista
def plot():
    pl = pv.Plotter()
    pl.add_mesh(pv.Sphere(), color="orange", show_edges=True)
    pl.view_isometric()
    return pl  # return the Plotter itself -- never call pl.show()

quickstart

Drag inside the view to rotate it, scroll to zoom – all of it happens in the browser, with nothing sent to Python.

Overview

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

Every pyvista Plotter works the same way: build it with add_mesh()/add_volume() calls like any pyvista script, then return it instead of calling .show().

Driving the view

A Shiny input drives both the 3D view and a second, Python-computed output, reading the same mesh object the render function used. Cache any expensive load or download in a @reactive.calc so it runs once, not on every input change – both examples below separate “build the base mesh” (cached) from “apply this render’s filter” (cheap, re-run per input).

Threshold slider

import pyvista as pv
from pyvista import examples
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_pyvista

pv.OFF_SCREEN = True

ui.page_opts(fillable=True)
ui.input_slider("threshold", "Bone-density threshold", 20, 200, 80, step=10)

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

        @reactive.calc
        def volume():
            # Downloaded and downsampled once per process, not per re-render
            v = examples.download_knee_full()
            dims = v.dimensions
            return v.extract_subset((0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1), (3, 3, 3))

        @reactive.calc
        def isosurface():
            return volume().contour([input.threshold()])

        @render_pyvista
        def plot():
            pl = pv.Plotter()
            pl.add_mesh(isosurface(), color="ivory", smooth_shading=True)
            pl.view_isometric()
            return pl

    with ui.card():
        ui.card_header("Computed from the same mesh, in Python")

        @render.code
        def stats():
            mesh = isosurface()
            return f"{mesh.n_points:,} points\n{mesh.n_cells:,} triangles\n{mesh.area:,.0f} units^2 surface area"

Dragging the threshold reshapes the extracted surface – the stats panel reads it straight off the mesh the plot just built:

Clip plane

import pyvista as pv
from pyvista import examples
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_pyvista

pv.OFF_SCREEN = True

ui.page_opts(fillable=True)
ui.input_slider("cut", "Clip position (fraction of width)", 0.0, 1.0, 0.5, step=0.05)


@reactive.calc
def terrain():
    # Mount St. Helens, downloaded once per process and cached across re-renders
    dem = examples.download_st_helens()
    return dem.warp_by_scalar()


@reactive.calc
def visible_terrain():
    x0, x1, *_ = terrain().bounds
    cut_x = x0 + input.cut() * (x1 - x0)
    return terrain().clip(normal="x", origin=(cut_x, 0, 0))


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

        @render_pyvista
        def plot():
            pl = pv.Plotter()
            pl.add_mesh(
                visible_terrain(), scalars="Elevation", cmap="terrain", show_scalar_bar=False
            )
            pl.view_isometric()
            return pl

    with ui.card():
        ui.card_header("Stats for the visible slab")

        @render.code
        def stats():
            mesh = visible_terrain()
            elev = mesh["Elevation"]
            return (
                f"{mesh.n_points:,} points visible\n"
                f"mean elevation: {elev.mean():,.0f} m\n"
                f"max elevation: {elev.max():,.0f} m"
            )

The same pattern reads any Shiny input: the “Switch the colored field” app in the Overview above recolors the mesh and updates a summary from a plain ui.input_select(), by switching which array add_mesh(scalars=...) points at.

Updating

pyvista has nothing to mutate in place: the only way to change what’s on screen is to have the render function build a new Plotter and return it.

The camera resets on every re-render, to whatever view_isometric()/camera_position the render function sets – never to wherever the user last dragged it:

import pyvista as pv
from pyvista import examples
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_pyvista

pv.OFF_SCREEN = True

ui.page_opts(fillable=True)
with ui.layout_columns(col_widths=12, fill=False):
    ui.input_action_button("iso", "Isometric")
    ui.input_action_button("top", "Top")
    ui.input_action_button("front", "Front")

view = reactive.value("iso")


@reactive.effect
@reactive.event(input.iso)
def _():
    view.set("iso")


@reactive.effect
@reactive.event(input.top)
def _():
    view.set("top")


@reactive.effect
@reactive.event(input.front)
def _():
    view.set("front")


@render_pyvista
def plot():
    pl = pv.Plotter()
    pl.add_mesh(examples.load_random_hills(), scalars="Elevation", cmap="terrain")
    {"iso": pl.view_isometric, "top": pl.view_xy, "front": pl.view_xz}[view()]()
    return pl

Dragging to rotate, then clicking a different preset button, jumps straight to that preset – the drag is gone:

Clicking the same preset button twice does nothing new, since nothing changed – easy to misread as a broken button while testing your own app.

Large data

Summarize on the server (see Large data & performance): decimate or downsample the mesh in Python before it’s exported, since every re-render re-sends the whole scene and cost scales with mesh size.

There’s no rate limiting of its own, so a free-running slider ships one export per tick – gate heavy meshes behind ui.input_action_button("update", ...) instead of a continuous slider. For picking or genuinely streamed updates at scale, reach for pyvista’s jupyter_backend="trame" path instead; this renderer doesn’t cover it.

Layout and sizing

import pyvista as pv
from pyvista import examples
from shiny.express import ui
from shinywidgets import render_pyvista

pv.OFF_SCREEN = True

ui.page_opts(fillable=True)


def make_plotter():
    pl = pv.Plotter()
    pl.add_mesh(examples.load_random_hills(), scalars="Elevation", cmap="terrain")
    pl.view_isometric()
    return pl


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

        @render_pyvista
        def fills():
            return make_plotter()

    with ui.card():
        ui.card_header("Explicit height")

        @render_pyvista(height="250px")
        def fixed_height():
            return make_plotter()

layout sizing

  • With no height (the default), the view fills its container – card, sidebar, full_screen, fillable page – and tracks resizes.
  • render_pyvista(height="250px") is respected exactly, independent of the surrounding card’s own height.
  • If you pre-build the widget yourself (trame_pyvista.jupyter.show_trame(pl, mode="html")) instead of returning the Plotter, pass width="100%", height="100%" explicitly – without them it keeps the plotter’s pixel window_size and sits small in the corner of a filling container instead of stretching to fit.
  • Frame the camera yourself (pl.view_isometric(), or an explicit camera_position). Pyvista’s default framing leaves wide margins around the mesh; every example above calls view_isometric() for exactly this reason.

Gotchas

  • Calling pl.show() instead of returning the Plotter renders a blank output, with only a UserWarning on the server console to explain why. Return the Plotter itself.
  • A Plotter closes once it’s rendered, so caching and reusing one across renders raises a ValueError. Construct a fresh Plotter in each render call.

Learn more