NGLView

A WebGL molecular structure viewer – proteins, nucleic acids, trajectories – as a reactive Shiny output.

NGLView is a Python wrapper around NGL, a WebGL viewer for macromolecular structures – cartoons, surfaces, ball-and-stick, and full playback of molecular-dynamics trajectories frame by frame. With @render_nglview, a click on an atom reaches your app as a full atom record, and the camera’s orientation through camera_orientation().

hero

Hemoglobin (PDB 4HHB), fetched live from RCSB by the browser. Try the app.

Installation

pip install 'shinywidgets[nglview]'

This installs nglview itself (an sdist that builds from source). Loading a trajectory additionally needs a structure/trajectory backend such as MDTraj (pip install mdtraj) or MDAnalysis; the trajectory examples below use MDTraj.

Quick start

nglview.show_file() (or show_text(), show_url(), show_structure_file()) builds an NGLWidget with a default cartoon representation. Nothing else is required – the viewer fills its card like any other shinywidgets output.

import nglview
from shiny.express import ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

with ui.card(full_screen=True):
    ui.card_header("Rhodopsin (PDB 1U19)")

    @render_nglview
    def structure():
        # nglview ships a few structures for examples/tests; no network needed
        view = nglview.show_file(nglview.datafiles.PDB)
        view.center()
        view.control.zoom(0.3)
        return view

quickstart

Overview

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

Viewer features

Where a structure comes from, how it’s drawn, and how to highlight part of it – the building blocks the rest of this guide uses.

Any structure source

show_file()/show_text()/show_structure_file() read on the server. show_url() instead queues a loadFile call that the browser fetches directly – the server never downloads the structure, which matters for a multi-user Shiny app. Avoid nglview.show_pdbid(): it calls urlopen() synchronously inside the render function, blocking that worker’s event loop (every session) until the download finishes.

import nglview
from shiny.express import input, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

ui.input_select(
    "source",
    "Structure source",
    {
        "bundled": "Bundled file (nglview.datafiles.PDB, no network)",
        "rcsb": "Fetched by the browser from RCSB (4HHB, hemoglobin)",
    },
)

with ui.card(full_screen=True):

    @render_nglview
    def structure():
        if input.source() == "bundled":
            # Read on the server; good for files you already have locally
            return nglview.show_file(nglview.datafiles.PDB)
        # show_url() queues a loadFile the *browser* fetches directly, so the
        # server never downloads the structure. Prefer this (or show_file/
        # show_text) over show_pdbid(), which blocks the server on urlopen().
        return nglview.show_url("https://files.rcsb.org/download/4HHB.cif")

Representations and coloring

NGL separates what’s drawn (representation: cartoon, licorice, spacefill, surface, …) from how it’s colored (scheme: by residue index, chain, B-factor, hydrophobicity, a custom scheme, …). Changing either from a @reactive.effect that mutates .widget restyles the live viewer – no re-render, so the user’s camera position survives.

import nglview
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

REPRESENTATIONS = ["cartoon", "licorice", "spacefill", "surface"]
COLOR_SCHEMES = ["residueindex", "chainindex", "bfactor", "hydrophobicity"]

with ui.sidebar():
    ui.input_select("representation", "Representation", REPRESENTATIONS)
    ui.input_select("color_scheme", "Color scheme", COLOR_SCHEMES)

with ui.card(full_screen=True):

    @render_nglview
    def structure():
        view = nglview.show_file(
            nglview.datafiles.PDB, default_representation=False
        )
        view.add_representation("cartoon", color_scheme="residueindex")
        view.center()
        return view

    # Restyle the already-rendered viewer in place instead of re-rendering:
    # the camera position and zoom survive, and the structure file isn't
    # re-sent to the browser
    @reactive.effect
    def _restyle():
        view = structure.widget
        if view is None:
            return
        view.clear_representations()
        view.add_representation(
            input.representation(), color_scheme=input.color_scheme()
        )

Selection language

NGL’s selection language picks out atoms by residue number ("262"), range ("260-265"), residue name ("LRT"), or keyword ("protein", "hetero"). Giving a highlight its own representation type (here, spacefill, distinct from the base cartoon) means remove_spacefill() clears only the highlight.

import nglview
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

ui.input_slider("residues", "Highlight residues", min=1, max=348, value=(260, 265))

with ui.card(full_screen=True):
    ui.card_header("Rhodopsin (1U19): highlight a residue range")

    @render_nglview
    def structure():
        view = nglview.show_file(
            nglview.datafiles.PDB, default_representation=False
        )
        view.add_representation("cartoon", color="lightgrey")
        view.center()
        return view

    # NGL's selection language ("262", "260-265", "LRT", "protein", ...) picks
    # out atoms by residue number, name, or keyword. A distinct representation
    # type (spacefill) for the highlight means remove_spacefill() only clears
    # it, leaving the cartoon representation untouched.
    @reactive.effect
    def _highlight():
        view = structure.widget
        if view is None:
            return
        lo, hi = input.residues()
        view.remove_spacefill()
        view.add_representation("spacefill", selection=f"{lo}-{hi}", color="red")

Trajectory playback

show_mdtraj() (or show_mdanalysis(), show_simpletraj()) loads every frame’s coordinates once; after that, setting .widget.frame streams just the new positions, so a Shiny slider with animate=True turns into a scrubbable molecular-dynamics movie.

# Needs mdtraj to load the bundled trajectory: `uv run --with mdtraj shiny run ...`
# (or `pip install mdtraj`; MDAnalysis works too, via nglview.show_mdanalysis()).
import mdtraj
import nglview
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

# A bundled 1 ns rhodopsin trajectory, 51 frames, 20 ps apart
traj = mdtraj.load(nglview.datafiles.XTC, top=nglview.datafiles.PDB)

ui.input_slider("frame", "Frame", min=0, max=traj.n_frames - 1, value=0, animate=True)

with ui.card(full_screen=True):

    @render_nglview
    def structure():
        return nglview.show_mdtraj(traj)

    # `frame` is a synced trait: setting it in place sends only the new
    # coordinates, not the whole structure again
    @reactive.effect
    def _scrub():
        view = structure.widget
        if view is not None:
            view.frame = input.frame()

trajectory

Reacting to interaction

NGLView has one curated reactive accessor, camera_orientation(); the other most useful interaction, clicking an atom, is a plain synced trait read with structure.read("picked").

Click an atom

A click fires picked twice: once with {} immediately (NGL clears the previous pick before raising the new one), then with the real record. Code that reads picked should treat {} as “nothing (yet)”, which picked.get("atom1") does naturally. The atom record has resname, resno, chainname, atomname, element, bfactor, x/y/z, index, serial, and name (a composed label like "[ASN]302:B.CA"). Clicking empty space resets picked to {} too, so there’s no separate “deselect” case to handle.

This example also highlights the clicked residue in place, combining the click-driven read with an in-place representation change:

import nglview
from shiny import reactive
from shiny.express import render, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

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

        @render_nglview
        def structure():
            view = nglview.show_file(
                nglview.datafiles.PDB, default_representation=False
            )
            view.add_representation("cartoon", color="lightgrey")
            view.add_representation("ball+stick", selection="hetero")
            view.center()
            return view

    with ui.card():
        ui.card_header("Picked atom")

        @render.text
        def atom_info():
            picked = structure.read("picked")
            atom = picked.get("atom1") if picked else None
            if atom is None:
                return "Click an atom in the structure."
            return (
                f"{atom['resname']} {atom['resno']} chain {atom['chainname']}\n"
                f"atom: {atom['atomname']} (element {atom['element']})\n"
                f"b-factor: {atom['bfactor']:.1f}"
            )

    # Highlight the clicked residue in place, on top of the cartoon
    @reactive.effect
    def _highlight_picked():
        view = structure.widget
        if view is None:
            return
        picked = structure.read("picked")
        atom = picked.get("atom1") if picked else None
        view.remove_spacefill()
        if atom is not None:
            view.add_representation(
                "spacefill", selection=str(atom["resno"]), color="orange"
            )

Read the camera

Dragging to rotate, scrolling to zoom, and right-click-dragging to pan all update the camera’s orientation, and structure.camera_orientation() reads it reactively. The accessor is opt-in – pass listen_to=["camera_orientation"] to @render_nglview. Reach for it if you want to save or restore a view, or log what orientation a user settled on.

import nglview
from shiny.express import render, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

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

        @render_nglview(listen_to=["camera_orientation"])
        def structure():
            view = nglview.show_file(nglview.datafiles.PDB)
            view.center()
            return view

    with ui.card():
        ui.card_header("Camera orientation (drag to rotate)")

        @render.code
        def orientation():
            # A 4x4 matrix (16 floats), updated ~100ms after the user stops
            # dragging/scrolling/panning the view (None until the first move)
            matrix = structure.camera_orientation()
            if matrix is None:
                return "Drag the view to rotate the camera."
            return "\n".join(
                " ".join(f"{v: .2f}" for v in matrix[i : i + 4])
                for i in range(0, len(matrix), 4)
            )

Updating in place

Every example above restyles or scrubs .widget from a @reactive.effect rather than returning a new widget from the render function. This matters more for NGLView than most widgets: a full re-render resets the camera to NGL’s default view, discarding any zoom, rotation, or pan the user has made, and re-sends the structure file to the browser. An in-place change (.widget.add_representation(...), .widget.frame = ..., .widget.clear_representations()) keeps the camera exactly where the user left it and sends only the small message the change requires.

import nglview
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

ui.input_action_button("restyle", "Restyle in place (keeps camera)")
ui.input_action_button("rerender", "Rerender (resets camera)")

rerender_count = reactive.value(0)

with ui.card(full_screen=True):

    @render_nglview
    def structure():
        rerender_count()  # a dependency here forces a full rebuild on "Rerender"
        view = nglview.show_file(nglview.datafiles.PDB, default_representation=False)
        view.add_representation("cartoon", color="lightgrey")
        view.center()
        return view

    @reactive.effect
    @reactive.event(input.rerender)
    def _force_rerender():
        rerender_count.set(rerender_count.get() + 1)

    # Changes representation without touching the render function, so the
    # camera (position, rotation, zoom) the user set by dragging is untouched
    @reactive.effect
    @reactive.event(input.restyle)
    def _restyle_in_place():
        view = structure.widget
        if view is not None:
            view.clear_representations()
            view.add_representation("surface", color="skyblue", opacity=0.6)

Drag to rotate, then restyle in place – the camera holds; only re-rendering resets it:

The rerender screenshot shows the camera snapped back to NGL’s default centered view, and the representation reset to the render function’s own cartoon – exactly the two things an in-place update preserves.

Linking widgets

Scrub or click to move through a trajectory, with an RMSD chart along for the ride – the richest pattern NGLView supports: a Shiny slider and a plotly chart’s clicked() accessor both drive one shared reactive.value, and three separate effects keep the viewer’s frame, the chart’s marker, and the slider all in sync – each one updating in place.

# Needs mdtraj to load the bundled trajectory: `uv run --with mdtraj shiny run ...`
import mdtraj
import nglview
import plotly.express as px
from shiny import reactive, req
from shiny.express import input, ui
from shinywidgets import render_nglview, render_plotly

ui.page_opts(fillable=True)

# A bundled 1 ns rhodopsin trajectory, 51 frames, 20 ps apart
traj = mdtraj.load(nglview.datafiles.XTC, top=nglview.datafiles.PDB)
ca = traj.topology.select("name CA")
rmsd = mdtraj.rmsd(traj, traj, 0, atom_indices=ca)

current_frame = reactive.value(0)

with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("Trajectory")

        @render_nglview
        def structure():
            return nglview.show_mdtraj(traj)

    with ui.card(full_screen=True):
        ui.card_header("RMSD to frame 0 (click a point to jump there)")

        @render_plotly
        def rmsd_plot():
            with reactive.isolate():
                start = current_frame.get()
            fig = px.line(
                x=list(range(len(rmsd))), y=rmsd, markers=True,
                labels={"x": "Frame", "y": "C-alpha RMSD (nm)"},
            )
            fig.add_vline(x=start, line_dash="dash", line_color="orange")
            return fig

ui.input_slider("frame", "Frame", min=0, max=traj.n_frames - 1, value=0, animate=True)


# The slider drives the shared frame value ...
@reactive.effect
def _slider_to_frame():
    current_frame.set(input.frame())


# ... and so does clicking a point on the RMSD plot, via plotly's clicked()
# accessor, keeping the slider in sync
@reactive.effect
def _chart_to_frame():
    pts = rmsd_plot.clicked()
    req(pts is not None)
    frame = int(pts["x"].iloc[0])
    current_frame.set(frame)
    ui.update_slider("frame", value=frame)


# Both the viewer and the plot's marker update in place: no re-render, so
# zoom/selection on the plot and the camera on the viewer are preserved
@reactive.effect
def _move_viewer():
    view = structure.widget
    if view is not None:
        view.frame = current_frame()


@reactive.effect
def _move_marker():
    fig = rmsd_plot.widget
    if fig is not None:
        frame = current_frame()
        with fig.batch_update():
            fig.layout.shapes[0].x0 = frame
            fig.layout.shapes[0].x1 = frame

Starting state, then after clicking the RMSD peak on the chart – the marker, the slider, and the 3D conformation all moved together:

Accessor reference

render_nglview declares one curated accessor, camera_orientation(), shown above. picked and frame are plain traits on the rendered NGLWidget itself, read with structure.read("trait") – every output’s generic trait-by-name reader, which falls through to reactive_read() on .widget under the hood. Reach for plain reactive_read(obj, "trait") instead only when the trait lives on a different widget than the one the renderer returns (there’s no such case in this guide).

Trait Returns Fires when Starting value Notes
"picked" dict the user clicks the viewer {} {} on every click too, briefly, before the atom record (see above); {} again if nothing is hit
"frame" int .widget.frame is set, from Python or synced back from a displayed trajectory player the render function’s initial value (usually 0) also settable from Python to drive playback
camera_orientation() (opt-in) list[float] (16-value flattened 4x4 matrix) the user drags, scrolls, or pans None debounced 250 ms by default; enable with listen_to=["camera_orientation"]

frame

Setting .widget.frame from Python (as in the playback example above) is the common direction. It’s also readable with structure.read("frame"), which matters when something other than your own code might move it – for example, a displayed trajectory player that the user drags directly. The trajectory + RMSD example reads frame indirectly, through a shared reactive.value that both a Shiny slider and a plot click can set.

Tuning accessors

Reading on demand

structure.read("picked") is live from the moment the viewer renders, not just from the moment something first reads it – so a button handler that fires long after the last click still sees it correctly, with no warm-up read needed first. That makes “build a list as you go” patterns simple: click a few atoms, then log the ones worth keeping.

import nglview
import pandas as pd
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_nglview

ui.page_opts(fillable=True)

log = reactive.value(pd.DataFrame(columns=["resname", "resno", "chain"]))

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):
        ui.card_header("Click an atom, then log it")

        @render_nglview
        def structure():
            view = nglview.show_file(
                nglview.datafiles.PDB, default_representation=False
            )
            view.add_representation("cartoon", color="lightgrey")
            view.add_representation("ball+stick", selection="hetero")
            view.center()
            return view

        ui.input_action_button("log", "Log current pick")

    with ui.card():
        ui.card_header("Logged residues")

        @render.data_frame
        def logged():
            return log.get()


# `picked` is live from the moment the viewer renders -- reading it here, in
# a button handler that may fire minutes after the last click, needs no
# warm-up read and never misses an interaction that happened before this
# ran.
@reactive.effect
@reactive.event(input.log)
def _log_pick():
    picked = structure.read("picked")
    atom = picked.get("atom1") if picked else None
    if atom is None:
        return
    row = {"resname": atom["resname"], "resno": atom["resno"], "chain": atom["chainname"]}
    with reactive.isolate():
        log.set(pd.concat([log.get(), pd.DataFrame([row])], ignore_index=True))

Click an atom, then click “Log current pick” – the residue is appended to the table on the right:

Rate limiting

Neither structure.read("trait") nor plain reactive_read() is rate-limited on its own – every change to the trait invalidates your reactive context immediately. In practice this rarely matters for NGLView: picked only changes on discrete clicks, not a stream; frame changes once per slider step or trajectory tick; and camera dragging already debounces by default (see the accessor reference above). To throttle further, wrap the read in your own @reactive.calc, or debounce the consuming output rather than the trait itself.

Large data

NGL draws with the GPU (WebGL) – see Large data & performance’s three approaches – so a single large assembly’s rendering cost is NGL’s own (see the upstream NGL docs for per-representation scale guidance). The scale question most relevant to a Shiny app is trajectories: show_mdtraj() loads every frame’s coordinates once, and after that, scrubbing with .widget.frame streams only the new frame’s positions, so long trajectories stay cheap to scrub once loaded.

Layout and sizing

The viewer fills its container by default – a ui.card(full_screen=True), a sidebar, a column – and tracks width (and height, if nothing claims it) as the container resizes, including on full_screen enter/exit and sidebar collapse. Three constructor-level overrides opt a viewer out of parts of that tracking, and shinywidgets honors all of them:

  • NGLWidget(height=...) (or show_file(..., height=...)): the viewer keeps that height and stops filling, but its width still tracks the container.
  • NGLWidget(width=...): the viewer keeps that width regardless of the container’s size.
  • widget.layout = Layout(width=..., height=...): both dimensions are pinned to the Layout.

For an explicit pixel size on the output instead of the widget, use output_widget("id", height="400px") as with any shinywidgets renderer.

Gotchas

  • The NGL GUI (view.gui_style = "ngl") renders unstyled, since Shiny doesn’t load the theme CSS a notebook would load automatically. Build your own Shiny inputs instead (as every example in this guide does).

Learn more