Package 'vellumwidget'

Title: Interactive Web Widgets for Vellum Scenes
Description: Turns a 'vellum' scene (or a 'vellumplot' plot) into a self-contained, client-side interactive HTML widget: hover tooltips and highlighting, click selection, rectangular brush-select, pan/zoom, and a toolbar -- driven by the per-element data keys, bounding boxes, and 'scene_model()' metadata that 'vellum' emits. Requires no Shiny and no server round-trip.
Authors: David Schoch [aut, cre]
Maintainer: David Schoch <[email protected]>
License: MIT + file LICENSE
Version: 0.19.1.9000
Built: 2026-11-24 07:59:02 UTC
Source: https://github.com/r-vellum/vellumwidget

Help Index


Turn a vellum scene (or vellumplot plot) into an interactive widget

Description

as_widget() is the terminal verb of the interactivity pipeline: it compiles its input to a vellum scene, emits the SVG (with per-element data-keys) and the vellum::scene_model() element table, and bundles them with the vellumwidget JavaScript runtime into a self-contained htmlwidgets::createWidget() widget. The result does hover tooltips, hover highlighting, and click selection entirely client-side — no Shiny, no server round-trip. Pan/zoom, brush, and selection work with mouse, touch (drag to pan, two-finger pinch to zoom), and keyboard input: the arrows pan and +/-/0 zoom and reset, except that with accessibility on (the default) the arrows move between marks while one is focused — see the a11y argument.

Usage

as_widget(
  x,
  width = NULL,
  height = NULL,
  toolbar = TRUE,
  navigator = FALSE,
  hover_mode = c("closest", "x", "y"),
  crosshair = FALSE,
  legend_click = c("select", "hide", "mute"),
  a11y = TRUE,
  alt = NULL,
  tooltip = tooltip_options(),
  export = export_options(),
  group = NULL,
  crosstalk = NULL,
  select_mode = c("multiple", "single"),
  render = render_options(),
  elementId = NULL,
  ...
)

Arguments

x

A vellumplot plot (a PlotSpec / PlotComposition) or a vellum scene — anything vellum::as_vellum_scene() accepts. Also a keyframe animation from vellumplot::animate(), embedded as a self-contained animated SVG (no per-element interaction). It autoplays and loops (set render = render_options(autoplay = FALSE, loop = FALSE) to change either), with playback controls in a row below the plot, where they never cover it: a play/pause button and a frame scrubber. Dragging the scrubber pauses on the chosen frame. When the reader's system asks for reduced motion (prefers-reduced-motion), the animation starts paused on its still frame; the button still plays it. Without JavaScript (the SVG on its own) it loops as before.

width, height

Widget size (any valid CSS size, or NULL to size from the scene). Passed to htmlwidgets::createWidget().

toolbar

Show the on-hover toolbar (default TRUE). Hover tooltip, highlight, click-select, brush, lasso, pan/zoom, and axis-aware zoom are on by default (interactive-by-default) and no longer have per-widget toggles; per-mark hover/select styling and selection-driven behaviour are declared in the plot spec instead (see vellumplot::condition() / vellumplot::select_point()).

navigator

Show an overview range navigator below the plot (default FALSE): a full-width strip rendering the whole scene in miniature, with a draggable, resizable window marking the visible x-range. Drag the window to pan, drag a handle to zoom; it stays two-way in sync with the main view (wheel/keyboard/brush and linked-group changes all move it). Useful for long series. TRUE shows it with the defaults; pass navigator_options() to show it and set its height.

hover_mode

How hover gathers marks into the tooltip. "closest" (default) shows the single nearest mark. "x" (or "y") gives a unified hover: every mark sharing the hovered x (or y) position is highlighted and listed together in one box — the shared readout multi-series line and time-series charts expect. Unified mode always snaps along its axis, so the readout tracks the cursor regardless of nearest. The mark positions come from the element index, so no axis metadata is required; the box lists each mark's tooltip (one row per series) without a value-axis header.

crosshair

Draw a guide rule at the hovered position (default FALSE): a vertical rule at the shared x when hover_mode = "x", a horizontal rule when "y", and a full cross through the mark when "closest". Colour is the --vellumwidget-crosshair-stroke CSS variable (a muted grey by default).

legend_click

What clicking a discrete-legend swatch does. "select" (default) selects the swatch's whole series (the established behaviour). "hide" makes the legend a visibility toggle — a single click hides/shows the series, a double-click isolates it (hides every other series; double-click again to restore all) — the reflexive legend interaction in plotly / ECharts / Highcharts. "mute" is the same but dims the series instead of removing it (its layout is kept). Hovering a swatch still highlights its series under every policy. Applies only where the plot draws an interactive legend (a discrete color / shape scale in vellumplot).

a11y

Accessibility (default TRUE). Makes the widget a keyboard- and screen-reader-navigable chart: the SVG is labelled as an interactive chart (role="graphics-document"), each mark is a focusable graphics-symbol with a roving tabindex (arrow keys move between marks, Enter/Space select, Escape exits), a polite aria-live region announces the focused/selected mark, and a visually-hidden data table lists every mark for assistive tech. FALSE restores the previous behaviour (no chart semantics, marks not focusable).

alt

Accessible label (alt text) for the chart as a whole. Defaults to the scene's own title/description — which vellumplot sets automatically from the plot title and vellumplot::plot_alt() — so an explicit value is only needed for a raw vellum scene or to override.

tooltip

Tooltip behaviour and style, from tooltip_options(): the show delay, whether the box follows the cursor, whether it is sticky, and the box style. NULL is the same as tooltip_options().

export

The toolbar's SVG/PNG download settings, from export_options(): the filename and PNG scale. NULL is the same as export_options().

group

Optional linking group name. Widgets sharing a group link client-side: selecting (or brushing) in one highlights the same data keys in the others, and panning/zooming one pans/zooms the others to the same relative view — no Shiny, no crosstalk. Selection projects by hover_group when the marks declare it (select one, select the whole series). Linked pan/zoom shares the view as a fraction of each widget's own extent, so it links correctly even across differently-sized plots (e.g. small multiples).

crosstalk

Optional crosstalk::SharedData (or a crosstalk group name string) to link this widget with the crosstalk ecosystem (plotly, leaflet, DT, and crosstalk's ⁠filter_*⁠ inputs). The widget's data_ids must match the SharedData's keys. A crosstalk filter hides the non-matching elements (display-tier cross-filter). Requires the crosstalk package.

select_mode

"multiple" (default; click toggles each element) or "single" (click replaces the selection).

render

How the marks are drawn, from render_options(): per-element SVG or a single raster image (mode), the element count at which "auto" switches to the image (raster_threshold), and how SVG text is written (text). NULL is the same as render_options().

elementId

Optional explicit widget DOM id.

...

Deprecated flat arguments, still accepted with a once-per-session warning: tooltip_delay, tooltip_follow, tooltip_sticky and tooltip_style (now tooltip = tooltip_options()), export_filename and export_scale (now export = export_options()), navigator_height (now navigator = navigator_options()), and mode, raster_threshold and text (now render = render_options()).

Details

Interactivity is driven by the keys/metadata a plot declares. In vellumplot these come from the reserved data_id / tooltip / hover_group mark arguments; a plot that declares none renders as a static (but still embeddable) SVG. A hovered element with a data_id but no tooltip shows its key.

Graph (vgraph()) plots that declare vellumplot::select_neighbours() are enacted here: hovering a node spotlights its neighbourhood (the node, its incident edges, and its adjacent nodes) and dims the rest, and hovering an edge spotlights its two endpoints. The adjacency is reconstructed from the endpoint identity each edge carries — no extra configuration.

The scene metadata vellumwidget reads — the vellum::scene_model() element table and the SVG data-key / ⁠data-vellum-*⁠ attributes — is specified in vellum's "The scene contract" vignette (vignette("scene-contract", package = "vellum")).

Value

An htmlwidget of class "vellumwidget".

See Also

tooltip_options(), export_options(), navigator_options() and render_options() for the grouped settings.

Examples

## Not run: 
library(vellumplot)
df <- data.frame(wt = mtcars$wt, mpg = mtcars$mpg, model = rownames(mtcars))
vplot(df) |>
  mark_point(x = wt, y = mpg, tooltip = model, data_id = model) |>
  as_widget()

# Grouped options
vplot(df) |>
  mark_point(x = wt, y = mpg, tooltip = model, data_id = model) |>
  as_widget(
    tooltip = tooltip_options(delay = 250, style = list(background = "#1d3557")),
    export = export_options(filename = "mtcars", scale = 2),
    render = render_options(mode = "svg")
  )

## End(Not run)

Drive an already-rendered widget from the Shiny server

Description

vellumwidget_proxy() is the server-to-client counterpart of the input read-back documented in vellumwidget-shiny. It returns a lightweight handle to a widget that is already on the page, so the server can change what the widget shows — set the selection, cross-filter it, zoom it — without re-rendering it (no renderVellumwidget() round-trip, no full redraw, no lost pan/zoom). This mirrors leaflet::leafletProxy() / DT::dataTableProxy() / plotly::plotlyProxy().

Usage

vellumwidget_proxy(outputId, session = NULL)

Arguments

outputId

The id of the vellumwidgetOutput() to control (the un-namespaced id, as passed to vellumwidgetOutput(); module namespacing is handled for you).

session

The Shiny session; defaults to the current reactive domain, so you rarely pass it explicitly.

Details

Call it inside an observe() / observeEvent() with the same outputId you gave vellumwidgetOutput(), then pipe the handle through one or more of the verbs below. Each verb sends a single custom message to the browser and returns the proxy invisibly, so calls chain with the pipe.

vw_select()

Replace the widget's selection with keys (the element data_ids). Selecting projects across a mark's hover_group and propagates to any linked / crosstalk widgets, exactly as a user click would, and updates ⁠input$<id>_selected⁠.

vw_clear_selection()

Clear the selection.

vw_filter()

Cross-filter: show only the elements whose key is in keys and dim/hide the rest (display tier — the data is untouched).

vw_clear_filter()

Remove the filter (show everything).

vw_zoom()

Zoom/pan the view to frame the elements in keys.

vw_reset_zoom()

Restore the original (full) view.

All keys are the element data keys — the data_id a vellumplot mark declares — the same identifiers you receive back through ⁠input$<id>_selected⁠ and friends.

Value

An object of class "vellumwidget_proxy" (invisibly from the verbs), to be piped into vw_select() and the other proxy verbs.

See Also

vw_select(), vw_filter(), vw_zoom(); vellumwidgetOutput() and vellumwidget-shiny for reading interactions back.

Examples

## Not run: 
library(shiny)
server <- function(input, output, session) {
  output$plot <- renderVellumwidget(my_widget)
  # A server-side control drives the plot without redrawing it:
  observeEvent(input$highlight, {
    vellumwidget_proxy("plot") |> vw_select(input$highlight)
  })
  observeEvent(input$reset, {
    vellumwidget_proxy("plot") |> vw_clear_selection() |> vw_reset_zoom()
  })
}

## End(Not run)

Proxy verbs: drive a rendered widget from the server

Description

Pipe a vellumwidget_proxy() handle through these to change what an already-rendered widget shows, without re-rendering it. Each sends one message to the browser and returns the proxy invisibly, so they chain.

Usage

vw_select(proxy, keys)

vw_clear_selection(proxy)

vw_filter(proxy, keys)

vw_clear_filter(proxy)

vw_zoom(proxy, keys)

vw_reset_zoom(proxy)

Arguments

proxy

A vellumwidget_proxy().

keys

Character vector of element data keys (the data_ids a vellumplot mark declares). For vw_select()/vw_filter() an empty vector is meaningful (select nothing / hide everything); use vw_clear_selection() / vw_clear_filter() to remove a selection or filter. For vw_zoom() an empty vector resets to the full view.

Value

The proxy, invisibly (for piping).

See Also

vellumwidget_proxy()


Shiny bindings for vellumwidget widgets

Description

Standard htmlwidgets output/render helpers so a vellumwidget widget can appear in a Shiny app or an interactive R Markdown document.

Usage

vellumwidgetOutput(outputId, width = "100%", height = "400px")

renderVellumwidget(expr, env = parent.frame(), quoted = FALSE)

Arguments

outputId

Shiny output slot id.

width, height

Widget size.

expr

An expression producing a vellumwidget widget.

env, quoted

Standard non-standard-evaluation plumbing.

Value

vellumwidgetOutput(): a Shiny output UI element. renderVellumwidget(): a Shiny render function.

Reading interactions server-side

A widget rendered as vellumwidgetOutput("plot") reports the user's interactions back to the server as reactive inputs, keyed by the output id. All values are the element data keys (the data_id a vellumplot mark declares); map them back to your data by that key.

input$plot_selected

Character vector of the currently selected keys (click / brush / keyboard, and any selection arriving from a linked widget). Updates as state — re-selecting the same set is a no-op. character(0) when nothing is selected.

input$plot_click

A list list(key=) for each click; key is NULL for a click on empty space. An event input — fires on every click, even the same mark twice.

input$plot_hover

The hovered key, or NULL when the pointer leaves a mark. Updates as state (re-fires only when the hovered key changes).

input$plot_brush

A list list(keys=, x0=, y0=, x1=, y1=) when a brush (or lasso) gesture completes: the selected keys and the region's bounding rectangle in the scene's device-pixel (viewBox) coordinates. A lasso gesture also carries lasso = TRUE. When the plot carries a cartesian scale (a vellumplot plot), it also carries the region's data-space bounds ⁠x0d,y0d,x1d,y1d⁠ and the panel name. When the plot declares a vellumplot::select_interval(), it also carries selection (the selection's name) and interval (per encoding, the brushed data range c(lo, hi), or the brushed levels on a discrete axis), and clearing the brush sets it to NULL. An event input.

input$plot_colorfilter

A length-2 numeric c(lo, hi) — the value range selected on a continuous colorbar (see the interactive colorbar filter); NULL when the full range is shown. State input.

input$plot_zoom

A list list(x=, y=, w=, h=, zoomed=) — the current view (the SVG viewBox in device-pixel coordinates) plus a zoomed flag (is the view narrower/shorter than the full extent). A cartesian plot also carries panels, a list keyed by panel id ("panel-1-1", ...) with each panel's visible range in data coordinates, list(x=c(lo,hi), y=c(lo,hi), panel=), or NULL for a panel scrolled out of view. Facets zoom per panel, so read panels for a faceted plot. A single-panel plot keeps the older data field, the same range as its one panels entry. A composition names its panels per cell ("cell-1-panel-1-1", "cell-2-panel-1-1", ...). When a vellumplot::bind_scale() zooms a panel to an interval selection, the panel's entry is its bound range and bound maps each bound panel id to the selection driving it. With binds in a composition each cell zooms on its own (a wheel or pan moves only the cell under the pointer, and a bound axis follows its selection), so x..h are the last-zoomed cell's view and zoomed is TRUE while any cell is zoomed in. Binds are enacted in SVG mode, and in raster mode with a vellum that has the split render (render_options(mode = "raster"), or "auto" above the threshold); with an older vellum a raster render ignores them. Updates as state when a zoom/pan settles (wheel, drag-pan release, pinch, keyboard, reset, zoom-to-selection, a proxy vw_zoom(), or a brush that moves a bound panel).

Data-space coordinates (x0d/…, zoom$data and zoom$panels) come from the per-panel scale descriptors vellumplot attaches to the scene; a raw vellum scene or a non-cartesian coordinate system carries none, and only the device-pixel fields are reported. Some specifics:

  • They describe the visual axes: x0d/x1d (and zoom$data$x) are the horizontal axis. Under coord_flip() that is the plot's y aesthetic.

  • Date/time axes report the numeric epoch (days for Date, seconds for POSIXct); map back with as.Date() / .POSIXct().

  • A discrete axis reports fractional band positions (category i sits at i), not the level labels.

  • Axes built with a custom ⁠scales::transform_*()⁠ object (anything beyond identity / log10 / sqrt / reverse) can't be inverted client-side, so that axis is omitted from the data-space fields (device-pixel fields still report).

These are emitted only inside a live Shiny session; a static render (knitr, pkgdown, htmltools::save_html()) produces identical output and no input traffic. To drive the widget from the server — set the selection, cross-filter it, or zoom it without a re-render — use vellumwidget_proxy().

See Also

as_widget()


Option helpers for as_widget()

Description

These helpers group related as_widget() settings into one argument each:

Usage

tooltip_options(delay = 0, follow = TRUE, sticky = FALSE, style = NULL)

export_options(filename = "plot", scale = 1)

navigator_options(height = 56)

render_options(
  mode = c("auto", "svg", "raster"),
  raster_threshold = 20000L,
  text = c("native", "outline"),
  max_marks = 2000000L,
  detail_marks = 3000L,
  precision = c("compact", "f32"),
  max_zoom = 100,
  autoplay = TRUE,
  loop = TRUE
)

Arguments

delay

Milliseconds to wait before the tooltip appears on hover (default 0, i.e. immediate). The highlight is unaffected — only the tooltip waits. A short delay (e.g. 250) calms a dense scatter.

follow

When TRUE (default) the tooltip tracks the cursor; when FALSE it anchors above the hovered mark's centre.

sticky

When TRUE, the tooltip accepts pointer events and lingers briefly when you leave the mark, so you can move into it — for tooltips that contain links or buttons (build the HTML via ⁠tooltip =⁠ in the plot). Default FALSE.

style

Optional named list styling the tooltip box: background / color (any R or CSS colour), fontsize, and max_width (any CSS length; a bare number is used as is). NULL (default) uses the built-in style. Tooltip text is rendered as safe HTML — an author-built ⁠tooltip =⁠ (e.g. via glue()) may use ⁠<b>⁠/⁠<i>⁠/⁠<br>⁠ for bold/italic/line breaks; data values are escaped and only those inert tags are honoured (no scripts/attributes).

filename

The download filename base, without extension (default "plot").

scale

The PNG resolution multiplier (default 1). Exports capture the current (zoomed/panned) view.

height

Height of the navigator strip in pixels (default 56). Passing navigator_options() to as_widget(navigator = ) turns the navigator on; navigator = TRUE is the same as navigator = navigator_options().

mode

Rendering strategy for the marks. "auto" (default) ships a per-element SVG for small/moderate plots and switches to a single embedded raster image above raster_threshold keyed elements; "svg" always uses the per-element SVG; "raster" always uses the image. In raster mode the marks are drawn once as a base image and all interaction (hover, click, brush, pan/zoom) is driven client-side from the element index (geometry + boxes + keys), so a very large scatter (100k+ points) stays navigable with a tiny DOM and a small payload. With a vellum that has the split render (⁠layer =⁠ on vellum::scene_svg()), only the keyed marks are an image: the axes, gridlines, legend and text stay SVG, so axis-aware zoom re-ticks the real axes, and the navigator and vellumplot::bind_scale() work as in SVG mode. With a vellum that also splits the furniture by paint order, what was drawn after the marks (a reference line or annotation added after the points) stays on top of them. An older vellum draws the whole scene as one image, and zoom then magnifies it. The trade-offs of raster mode: there are no per-element DOM nodes until the detail tier (see detail_marks), so hover and selection show as rings and per-mark screen-reader focus is off. Zoomed in, the marks are redrawn exactly from vellum's marks-only display list (see max_marks), or as plain dots with an older vellum. With the display list, vellumplot::condition() colours and dimming, vellumplot::filter_by(), cross-filters and legend hide/mute show at every zoom: the marks are then drawn on a canvas from the list. Without it (an older vellum, or more marks than max_marks), and for marks the list cannot reproduce (gradients, grouped marks), these show only in the detail tier.

raster_threshold

Keyed-element count above which mode = "auto" switches to the raster image (default 20000).

text

How text is written into the SVG, passed to vellum::scene_svg(): "native" (default) emits selectable ⁠<text>⁠ referencing system fonts — smaller when the page has the font, post-processable, and better for accessibility and LLMs; "outline" emits glyph outlines that are pixel-faithful and font-independent but not selectable. Applies to the SVG, including raster mode's SVG furniture under the split render; with an older vellum, raster mode bakes text into the base image and this argument is ignored (with a warning if set explicitly).

max_marks

In raster mode with a vellum that has the marks-only display list, the most marks whose exact geometry and paint ship with the widget (default 2000000). Zoomed-in marks are then redrawn exactly, with their own shape, colour, stroke and alpha. With precision = "compact" a scatter's widget takes about 6 MB per million points (1 million: 6.2 MB, 2 million: 12.2 MB, keys included) and about 5 s per million to build. Above it, the widget ships only a bounding-box index, about as big (6.3 MB per million), draws zoomed-in marks as plain dots (each in its own mark's colour), and says so with a message: a plot that big is better drawn as density, with vellumplot::mark_datashade() or vellumplot::mark_hex().

detail_marks

In raster mode with the display list, once a zoom settles with fewer than this many marks in view (default 3000), the visible marks become real SVG nodes (the detail tier): hover, selection, condition() and filter_by() styling and keyboard focus then work on them as in SVG mode. Zooming back out past 1.5 times this many returns to the canvas. 0 turns the detail tier off.

precision

How the display list ships its marks' coordinates (see max_marks). "compact" (default), with a vellum that supports it, quantises each coordinate column within its range so that no coordinate is off by more than 0.005 px, the precision of the SVG vellum writes (SVG mode, and raster mode's axes and gridlines): 16 bits per value for a plot up to 655 px across, 24 above, instead of a 32-bit float. That halves the coordinates in the payload (a 200k-point scatter: 2.7 to 1.7 MB) and keeps the error under half a pixel up to 100x zoom. "f32" ships 32-bit floats, as an older vellum always does.

max_zoom

The most the view zooms in, per axis, over the full view (default 100), in SVG and raster mode alike: the wheel, pinch, keys, box zoom and zoom-to-selection, vw_zoom(), linked views (⁠group =⁠) and vellumplot::bind_scale() all stop there. At 100x the 0.01 px grid vellum writes SVG coordinates on (and the 0.005 px error of precision = "compact") is still within half a screen pixel, so the marks stay on their gridlines; past it they drift (a few pixels at 1000x) and show only the rounding. A number from 1 (no zoom in) to 10000: past about 16,000x a 32-bit float can no longer place a mark at all.

autoplay, loop

For an animation (from vellumplot::animate()): whether it starts playing as soon as it is shown (default TRUE; FALSE starts paused on the first frame, for the reader to press play), and whether it loops (default TRUE; FALSE plays once and stops on the last frame, and pressing play there starts it over). A reader whose system asks for reduced motion always gets it paused. They need JavaScript: the animated SVG on its own always plays and loops. Ignored for a static plot.

Details

  • tooltip_options() for the hover tooltip (as_widget(tooltip = ));

  • export_options() for the toolbar's SVG/PNG download (as_widget(export = ));

  • navigator_options() for the overview range navigator (as_widget(navigator = ));

  • render_options() for how the marks are drawn (as_widget(render = )).

Each validates its arguments and returns an object that as_widget() reads. Calling a helper with no arguments gives the defaults.

Value

An object of class vellumwidget_tooltip_options, vellumwidget_export_options, vellumwidget_navigator_options or vellumwidget_render_options, to pass to the matching as_widget() argument.

Examples

tooltip_options(delay = 250, style = list(background = "#1d3557"))
export_options(filename = "mtcars", scale = 2)
navigator_options(height = 80)
render_options(mode = "raster")

## Not run: 
library(vellumplot)
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, tooltip = rownames(mtcars)) |>
  as_widget(
    tooltip = tooltip_options(delay = 250, follow = FALSE),
    export = export_options(filename = "mtcars", scale = 2)
  )

## End(Not run)