Package 'vellumplot'

Title: A Grammar of Graphics on the 'vellum' Backend
Description: A declarative, pipe-first grammar of graphics that compiles an inspectable plot specification into a 'vellum' scene and renders it. A plot is built up as a serializable spec (data, layers, scales) and nothing is drawn until it is compiled: encodings are resolved, scales are trained, a panel layout is measured, and guides and marks are emitted as 'vellum' grobs.
Authors: David Schoch [aut, cre]
Maintainer: David Schoch <[email protected]>
License: MIT + file LICENSE
Version: 0.21.1.9000
Built: 2026-11-23 23:41:31 UTC
Source: https://github.com/r-vellum/vellumplot

Help Index


Add marginal distributions to a plot

Description

add_marginal() draws a distribution of the panel's x variable along the top edge and/or of its y variable along the right edge, each sharing the main panel's axis so it lines up with the scatter (the vellumplot analogue of ggExtra::ggMarginal()). It is a plot-level modifier, like facet_wrap() or coord_flip(): it takes no encoding of its own and instead reads x, y (and, with group = TRUE, color) from the first layer that maps a numeric x and y (typically your mark_point()).

Usage

add_marginal(
  plot,
  type = c("density", "histogram"),
  sides = "tr",
  size = 0.15,
  adjust = 1,
  bins = 30,
  group = FALSE
)

Arguments

plot

A PlotSpec (from vplot()) with at least one x/y layer.

type

The marginal distribution: "density" (a kernel-density curve, the default) or "histogram" (binned counts).

sides

Which edges to draw, as a string of "t" (top, the x distribution) and/or "r" (right, the y distribution). Default "tr".

size

The marginal size as a fraction of the panel, in ⁠(0, 1)⁠.

adjust

Bandwidth multiplier for type = "density" (see mark_density()).

bins

Number of bins for type = "histogram" (see mark_histogram()).

group

When TRUE and the plot maps color/fill to a discrete variable, draw one distribution per group in the matching colour (like ggMarginal(groupColour = TRUE)). The scatter's legend already covers them, so no extra legend is added.

Details

The marginals are drawn without their own axes or background. This version supports a single panel only: combining it with facet_wrap() / facet_grid(), a non-Cartesian coordinate system (coord_flip(), coord_polar(), coord_fixed(), coord_sf()), or a locked aspect ratio is an error.

Value

The modified PlotSpec.

See Also

mark_density(), mark_histogram(), facet_wrap()

Examples

vplot(faithful) |>
  mark_point(x = eruptions, y = waiting) |>
  add_marginal()

vplot(faithful) |>
  mark_point(x = eruptions, y = waiting) |>
  add_marginal(type = "histogram", sides = "t")

Register a free-standing selection on a plot

Description

Attach a SelectionSpec (from the free-standing form of select_point() / select_interval()) to a plot, marking that the selection's gesture is active on this plot's marks. Use it when a selection is defined once and shared across views in a composition (define + add_selection() on one plot, filter_by() on another).

Usage

add_selection(plot, selection)

Arguments

plot

A PlotSpec.

selection

A SelectionSpec.

Value

The PlotSpec, with the selection registered.

See Also

select_point(), filter_by()


Map an aesthetic to a statistic computed by a stat

Description

Used inside a ⁠mark_*()⁠ encoding to reference a variable produced by the layer's statistical transform rather than a raw data column, e.g. y = after_stat(count) or y = after_stat(density).

Usage

after_stat(x)

Arguments

x

An expression in terms of the stat's computed variables.

Value

Its argument (the marker is interpreted at compile time).


Save one frame of an animation as a still image

Description

anim_frame() writes a single frame of a vellum_animation to a PNG, SVG or PDF file: the poster for an animation, its thumbnail, or the moment to put in print. The frame is drawn exactly as it appears in the animation – the same frozen scales and colours, the same tween, the same frame variables in the title – so a poster matches the animation it stands for, which a separately built static plot (its scales trained on one state) need not.

Usage

anim_frame(filename, animation, frame = NULL, scale = 1)

Arguments

filename

Output path; .png, .svg or .pdf.

animation

A vellum_animation (from animate()).

frame

The frame to save: a whole number from 1 to the number of frames. The default is the frame a reader who asks for reduced motion sees: the last frame when the animation ends on its final state (a reveal, transition_time(), a non-looping transition_states()), else the first.

scale

Resolution multiplier (default 1), as in render_plot(): 2 doubles the pixels of a PNG at the same layout.

Details

Frames are numbered as in the files anim_save() writes, pauses and rewind included (see animate()).

Value

filename, invisibly.

See Also

anim_save(), animate()

Examples

## Not run: 
d <- data.frame(t = rep(1:3, each = 4), g = rep(letters[1:4], 3),
                v = c(1, 3, 2, 4, 4, 1, 3, 2, 2, 4, 1, 3))
a <- vplot(d) |>
  mark_bar(x = g, y = v, fill = g) |>
  transition_states(t, wrap = FALSE) |>
  animate()
anim_frame("poster.png", a) # the final state
anim_frame("middle.svg", a, frame = 25)

## End(Not run)

Write a keyframe animation to a file

Description

anim_save() renders a vellum_animation (from animate()) to an animated image, tweening the frames between keyframes and encoding them in one parallel, streaming pass in vellum's Rust backend. The format follows the file extension:

Usage

anim_save(filename, animation)

Arguments

filename

Output path; .gif, .png/.apng, or .svg.

animation

A vellum_animation (from animate()).

Details

  • .gif — a looping GIF (universal compatibility).

  • .png or .apng — an animated PNG (APNG; lossless, alpha). Browsers play either; .png is the more widely recognised extension, and image viewers that do not know APNG show its first frame.

  • .svg — a single animated SVG: every frame is emitted as vector markup and shown in turn by a CSS step animation. It is resolution-independent (crisp at any size, in print and on retina) and honours prefers-reduced-motion (a reader who has asked their system not to animate gets the first frame, held).

Value

filename, invisibly.

Choosing a format

Pick by scene complexity, not preference. An animated SVG emits every frame in full, so its size grows with the number of marks times the number of frames; a raster format (GIF/APNG) does not. So SVG wins clearly on line art — a few moving marks, the common explanatory case — and loses on a dense scatter, where a raster format is the right answer. anim_save() says so when a .svg scene is dense enough that a raster format would likely be smaller.

Video (.mp4, .webm, ...) and animated WebP are not written: there is no encoder for them among vellum's dependencies. Save an APNG or GIF and convert it, e.g. ⁠ffmpeg -i anim.png -pix_fmt yuv420p anim.mp4⁠, or magick::image_write(magick::image_read("anim.gif"), "anim.webp").

See Also

animate()

Examples

## Not run: 
# Four bars in every state, so each bar tweens into its next height.
d <- data.frame(t = rep(1:3, each = 4), g = rep(letters[1:4], 3),
                v = c(1, 3, 2, 4, 4, 1, 3, 2, 2, 4, 1, 3))
a <- vplot(d) |>
  mark_bar(x = g, y = v, fill = g) |>
  transition_states(t) |>
  animate()
anim_save("bars.gif", a)
anim_save("bars.svg", a) # resolution-independent

## End(Not run)

Build a keyframe animation from a plot

Description

animate() compiles a plot carrying a transition_states() into one keyframe scene per state, training the scales once over all states and freezing them, and returns a vellum_animation. Write it with anim_save(); printing it shows the first keyframe as a preview.

Usage

animate(
  plot,
  nframes = 50,
  fps = 25,
  start_pause = 0,
  end_pause = 0,
  rewind = FALSE
)

Arguments

plot

A PlotSpec with a transition_states() (and optionally an ease_aes()).

nframes

Total number of frames to render, a positive whole number. The pauses and the rewind are part of it, as in gganimate.

fps

Frames per second (the playback rate written into the file).

start_pause, end_pause

Number of frames to hold the first and the last frame for, before the animation starts and after it ends (default 0). A looping file (every format loops) then rests on the final picture before starting over: end_pause = fps holds it for a second.

rewind

Play the animation backwards after it has played forwards, so the loop returns to its start smoothly instead of cutting (default FALSE). The frames are split between the two directions; the end pause sits between them and the start pause at both ends.

Details

Per-state statistics (e.g. a smooth) are recomputed per keyframe, but no scale domain retrains — the frozen scales are the observable proof the animation stayed non-reactive (axis breaks do not move between frames).

Value

A vellum_animation.

Which mark becomes which

Marks tween by identity, as gganimate matches by group: each mark of one state moves into the mark that is the same thing in the next state, however the rows are ordered and whatever groups each state contains. A mark's identity is

  1. its data_id, when the layer declares one (mark_point(data_id = country)): the way to follow individual observations;

  2. otherwise its group – the group aesthetic if mapped, else the combination of the layer's discrete mapped aesthetics (color, fill, shape, ..., and a discrete x, y or label) – so a bar race's bars, filled by country, slide between ranks keeping their colours;

  3. and within a group, the order of its rows – the last resort, enough when each group has one mark per state, but rows of one group pair up by position. Give such a layer a data_id (or a group) when its rows are individual observations whose order may change.

A line, path or area is one mark per series and is matched by its group.

A faceted plot animates panel by panel: every panel of the whole data is drawn in every frame (a state without rows for a panel leaves it empty rather than dropping it), and a mark's identity includes its panel, so a mark never slides from one panel into another – a row whose facet value changes between states fades out of one panel and into the other. The scales are frozen across frames, so per-panel scales (facet_wrap(scales = "free"), an independent resolve_scale()) are refused.

A mark found in only one of two adjacent states fades in or out (points, bars and tiles, labels, lines and areas alike, with their effect underlays such as glow()) on the alpha easing, and a point whose colour group changes slides to its new place while its colour blends. A line, path or area whose number of points changes morphs from one outline into the other. Where marks overlap, the stacking order switches to the next state's halfway through the transition. What cannot move switches whole halfway through: decoration without an identity that comes and goes, or a line that cannot be morphed (a broken line with missing values, mixed units). animate() warns (once per call) when that will happen, naming the states.

Give each transition enough frames to be seen: nframes is spread over all the states, so 40 states in 80 frames leave two frames per state and nothing visibly moves.

Frame variables

A title, subtitle or caption (set with labs()) may embed frame variables in braces, glue-style, as in gganimate: labs(title = "Year: {frame_time}"). Each {...} is an R expression evaluated per frame with the variables below in scope (and the environment animate() was called from behind them), so "{round(frame_time)}" or "{format(frame_time, '%Y')}" work; write ⁠{{⁠ and ⁠}}⁠ for literal braces. The label is updated on every frame, not only at keyframes: a {frame_time} title counts through the in-between times while the marks move.

  • every transition: frame (the frame number), nframes, progress (frame / nframes);

  • transition_states(): closest_state, previous_state, next_state (the state the frame is nearest to, comes from and goes to; all three are the held state during a pause) and transitioning (TRUE while moving). closest_state switches halfway through a transition, on the position easing, when the marks' discrete attributes do;

  • transition_time(): frame_time, the time the frame has reached (on the position easing, so it agrees with where the marks are), of the time column's class (Date, POSIXct, or double);

  • transition_reveal(): frame_along, the along value revealed so far.

A mark_text() label can use the same variables (VP-93): mark_text(data = data.frame(x = 3000, y = 40), x = x, y = y, label = "{round(frame_time)}", size = 60) draws the year large behind a gapminder bubble chart, counting on every frame. A constant label or a column of labels may contain {...}; the label is placed (and moves) as the mark it belongs to, and only its string changes per frame. Repelled and rich-text labels are not templated. An ordinary data label whose string differs between two states takes the nearer state's string, switching halfway through.

Pauses and rewind

start_pause and end_pause hold the first and last frame for that many frames, and rewind = TRUE plays the animation back to the start, as in gganimate. They come out of nframes: animate(nframes = 100, end_pause = 20) moves for 80 frames and rests on the final picture for 20. Every output honours them – anim_save() to GIF, APNG or SVG, anim_frame()'s frame numbers, and the frame scrubber of an animated vellumwidget.

See Also

transition_states(), ease_aes(), anim_save(), anim_frame()

Examples

## Not run: 
# Four bars in every state, so each bar tweens into its next height.
d <- data.frame(t = rep(1:3, each = 4), g = rep(letters[1:4], 3),
                v = c(1, 3, 2, 4, 4, 1, 3, 2, 2, 4, 1, 3))
vplot(d) |>
  mark_bar(x = g, y = v, fill = g) |>
  transition_states(t) |>
  animate(nframes = 60, fps = 25)

## End(Not run)

Add a one-off annotation

Description

Draw a single mark (or a short vector of them) from values supplied directly, rather than mapping a data column. The values become a small inline layer data frame, so annotations are independent of the plot data (and repeat on every facet panel). Supported geoms: "text", "label", "point", "segment", "rect", "grob", and "sparkline".

Usage

annotate(
  plot,
  geom,
  x = NULL,
  y = NULL,
  xend = NULL,
  yend = NULL,
  xmin = NULL,
  xmax = NULL,
  ymin = NULL,
  ymax = NULL,
  label = NULL,
  ...
)

Arguments

plot

A PlotSpec.

geom

The annotation geometry: one of "text", "label", "point", "segment", "rect", "grob", "sparkline".

x, y

Position (text/label/point/grob/sparkline; segment start).

xend, yend

Segment end.

xmin, xmax, ymin, ymax

Rectangle extent.

label

Text to draw (text/label).

...

Constant aesthetics passed to the mark (e.g. color, fill, alpha, size). For "grob": ⁠grob =⁠ (a vellum grob or PlotSpec). For "sparkline": ⁠values =⁠ plus any vsparkline() argument. Both accept width/height/units (the box, default ⁠20 x 6⁠ mm) and halign ("left"/"centre"/"right") / valign ("top"/"centre"/"bottom") to anchor the box relative to ⁠(x, y)⁠.

Details

"grob" places an arbitrary vellum grob (or a PlotSpec, e.g. a vsparkline()) at data coordinate(s), in a box of physical size — a general "glyph / chart in a panel" seam. "sparkline" is the convenience for the common case: pass ⁠values =⁠ and it builds and places a vsparkline().

Value

The modified PlotSpec.

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  annotate("text", x = 4, y = 30, label = "note") |>
  annotate("rect", xmin = 3, xmax = 4, ymin = 15, ymax = 20, alpha = 0.2)
## Not run: 
vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  annotate("sparkline", x = 4, y = 30, values = cumsum(rnorm(30)))

## End(Not run)

Define a layout area for ⁠design =⁠

Description

An area() is a rectangular block of grid cells (1-based, inclusive) that a sub-plot occupies. Pass a list of area()s (one per plot, in order) as concat(..., design = ) to place plots on an explicit, possibly spanning, grid.

Usage

area(t, l, b = t, r = l)

Arguments

t, l, b, r

Top, left, bottom, right cell indices (1-based, inclusive).

Value

An area spec.

Examples

a <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
b <- vplot(mtcars) |> mark_point(x = hp, y = mpg)
concat(a, b, design = list(area(1, 1, 1, 2), area(2, 1, 2, 1)))

Serialize a plot to a plain spec (and back)

Description

as_spec() turns a PlotSpec into a plain, nested, serializable R list (data, layers, encodings, scales, coordinates, facets, labels, page size); from_spec() rebuilds a PlotSpec from that list. Together with spec_to_json() / spec_from_json() this makes a vellumplot plot a portable document — the substrate for the LLM / agent tooling (spec_fields(), vplot_from_spec()) and the Vega-Lite bridge (spec_to_vegalite()).

Usage

as_spec(plot)

from_spec(spec, data = NULL, env = globalenv())

Arguments

plot

A PlotSpec.

spec

A spec list from as_spec().

data

Optional data frame to render the spec against. Required when the spec stores its data by reference; for a spec that inlines its data (or has no data block), a supplied data takes precedence over the inlined copy.

env

The environment channel expressions are re-quoted in (default the global environment).

Details

The spec is a subset of the full grammar — the encoding-level state that a portable document can carry faithfully. State that a JSON document cannot represent (custom transform functions, paint/pattern fills, hand-drawn sketch() geometry, secondary axes, sf CRS objects, per-layer data) is refused with a classed vellumplot_unserializable error naming the exact slot — it is never silently dropped. The single exception is theme element customisation, which is styling orthogonal to the data spec: the theme preset name and its scalar settings round-trip, but custom ⁠element_*()⁠ overrides are dropped with a warning.

Channel expressions are stored as text (a column name, or an expression like log(x)); the quosure's captured environment is dropped, so an encoding that closes over a local variable will not round-trip.

Data is inlined when small (at most a few thousand cells and all-atomic columns) and otherwise stored by reference (name + content hash + column schema); a by-reference spec needs from_spec(spec, data = ) to recompile.

Value

as_spec() returns a named list; from_spec() returns a PlotSpec.

See Also

spec_to_json(), spec_to_vegalite(), vplot_from_spec()

Examples

p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = cyl)
spec <- as_spec(p)
spec$layers[[1]]$mark
p2 <- from_spec(spec)

Classify two variables for a bivariate map

Description

bi_class() bins two numeric columns into dim classes each and adds one column holding the pair of classes as "x-y" ("1-1" is low on both, "3-3" high on both at dim = 3). Map a fill to that column and add scale_fill_bivariate() to colour it with a bivariate palette and draw the 2-D legend. The design follows the biscale package's bi_class().

Usage

bi_class(data, x, y, dim = 3, style = "quantile", name = "bi_class")

Arguments

data

A data frame or sf object.

x, y

The two numeric variables (bare column names). x runs along the legend's horizontal axis, y up its vertical one.

dim

Classes per variable: 2, 3 (default) or 4.

style

How to choose the class breaks: "quantile" (default), "equal", "pretty", or any classInt::classIntervals() style (needs the classInt package) — the same styles as scale_fill_binned().

name

Name of the new column (default "bi_class").

Details

Classes are computed over the whole table, so a faceted map shares one set of breaks across its panels. bi_class() works on a plain data frame or an sf table (the geometry is kept). It records the two variable names on the new column, which scale_fill_bivariate() uses as the legend's axis titles when you don't give your own.

Value

data with a factor column name whose levels are all dim^2 classes in order. Rows where x or y is missing get NA.

See Also

scale_fill_bivariate(), bi_pal()

Other bivariate: bi_pal(), guide_bivariate(), scale_fill_bivariate()

Examples

d <- bi_class(mtcars, hp, wt)
table(d$bi_class)

Bivariate palettes

Description

bi_pal() returns the colours of a bivariate palette: a dim x dim matrix of colours, one per pair of classes, flattened to a vector named by class ("1-1", "2-1", ..., "3-3"; the first number is the x class, the second the y class). It is what scale_fill_bivariate() colours each class with.

Usage

bi_pal(palette = "DkBlue", dim = 3)

Arguments

palette

A palette name: "DkBlue" (default), "GrPink", "DkViolet" or "Brown".

dim

Classes per variable: 2, 3 (default) or 4.

Details

The built-in palettes are Joshua Stevens' four 3x3 schemes; for dim = 2 and dim = 4 they are interpolated in Lab space from the 3x3 grid, so the corner colours are the same at every size. The lightest corner ("1-1") is low on both variables, the darkest ("3-3" at dim = 3) high on both.

Value

A named character vector of dim^2 colours.

See Also

bi_class(), scale_fill_bivariate()

Other bivariate: bi_class(), guide_bivariate(), scale_fill_bivariate()

Examples

bi_pal("GrPink")
bi_pal("DkBlue", dim = 2)

Bind a panel's view to a selection (overview + detail)

Description

Make the aes view of this plot's panel(s) follow an interval selection defined on another (overview) plot: brushing the overview zooms this (detail) view to the brushed range, and clearing the brush resets its zoom. It is Vega-Lite's scale = list(domain = list(param = "brush")): the selection names the detail view's domain. This is a display-tier view change (pan/zoom), not a scale retrain, so the detail keeps its own scales and its axes re-tick for the visible range.

Usage

bind_scale(plot, selection, aes = c("x", "y"))

Arguments

plot

A PlotSpec (the detail view).

selection

A SelectionSpec (an interval selection), or a name string.

aes

The axis to bind, "x" (default) or "y".

Details

The selection may be a brush or a bind = "scales" selection (then zooming the overview zooms the detail: linked zoom). aes must be one of the selection's encodings. Bind as many views as you like to one selection, and call bind_scale() twice ("x" and "y") to follow a rectangular brush on both axes. The panel the brush is drawn in never zooms itself.

Enacted by vellumwidget::as_widget() in SVG mode; under Shiny the detail's visible range is reported in ⁠input$<id>_zoom$panels⁠. A composition names its panels per cell ("cell-2-panel-1-1", ...), so each cell's range is addressable.

Value

The PlotSpec, with the bind registered.

See Also

select_interval()

Examples

df <- data.frame(t = 1:200, v = cumsum(rnorm(200)))
brush <- select_interval("brush", encodings = "x")
vconcat(
  vplot(df, height = 2) |> mark_line(x = t, y = v) |> add_selection(brush),
  vplot(df) |> mark_line(x = t, y = v) |> bind_scale(brush)
)

Clip or mask a plot to a geometry

Description

Restrict where a plot's marks show, by a shape rather than the panel rectangle. clip_to() is a hard clip: only marks inside region are drawn (or, with invert = TRUE, only those outside) – the way to fill a raster / hexbin / tile heatmap into a country outline (a textured choropleth). set_mask() is a soft mask: a radial luminance ramp that fades the panel out towards its edges (a vignette / spotlight).

Usage

clip_to(plot, region, invert = FALSE)

clip_layer(plot, region, invert = FALSE)

set_mask(plot, region = NULL, type = c("luminance", "alpha"), feather = 0.35)

Arguments

plot

A PlotSpec.

region

The clip geometry: an sf object (its polygons), or a data.frame / matrix with x / y columns (and an optional group column for several rings). For set_mask(), NULL (default) fades the whole panel.

invert

For clip_to(), TRUE keeps the marks outside region (punching the shape out as a hole) instead of inside.

type

For set_mask(), how the mask's pixels set coverage: "luminance" (default – brightness, white shows / black hides) or "alpha".

feather

For set_mask(), the soft-edge fraction of the radial ramp in ⁠[0, 0.9]⁠: 0 a hard disc, larger a gentler fade. Default 0.35.

Details

clip_to() / set_mask() mask the whole panel; clip_layer() masks only the most-recently-added layer (the one just piped in), so one raster layer can be clipped to a shape while the axes and other layers stay full-bleed.

All three attach to the plot and resolve at render into an isolated masked layer (vellum::as_mask()), so the static output is unchanged when none is set. Cartesian coordinates only (not polar or a nonlinear coord_trans()).

A smooth feathered edge on an arbitrary polygon needs a blur the renderer does not provide yet, so clip_to() is hard-edged; use set_mask() for a soft (radial) fade.

Value

The modified PlotSpec.

Examples

## Not run: 
# clip a raster heatmap to a country outline
vplot(grid) |> mark_raster(x = x, y = y, fill = z) |> clip_to(country_sf)

# a vignette
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> set_mask(feather = 0.5)

## End(Not run)

Annotate a composition

Description

Add figure-level text (a title, subtitle, caption) spanning the whole composition, and/or auto-tag the sub-plots (A, B, C, …). Because every PlotComposition carries its own annotation, this works at any nesting level (unlike patchwork, where annotation is top-level only).

Usage

compose_annotation(
  plot,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  tag_levels = NULL,
  tag_prefix = "",
  tag_suffix = ""
)

Arguments

plot

A PlotComposition (from concat() / hconcat() / vconcat()).

title, subtitle, caption

Figure-level text (or NULL).

tag_levels

Auto-tag style: "A", "a", "1", "i", or "I" (NULL = no tags).

tag_prefix, tag_suffix

Strings wrapped around each tag.

Value

The modified PlotComposition.

See Also

theme(), which also accepts a composition to set the figure-level chrome (title bands, collected legend, panel spacing, tags).

Examples

a <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
b <- vplot(mtcars) |> mark_point(x = hp, y = mpg)
hconcat(a, b) |> compose_annotation(title = "Fuel economy", tag_levels = "A")

Arrange plots side by side

Description

Compose several independent plots into one image. hconcat() lays them in a row, vconcat() in a column, and concat() on a grid of ncol/nrow cells. Each sub-plot keeps its own scales, axes, and legend (this is view composition, not faceting).

Usage

concat(
  ...,
  ncol = NULL,
  nrow = NULL,
  byrow = TRUE,
  widths = NULL,
  heights = NULL,
  guides = c("collect", "keep"),
  design = NULL,
  width = NULL,
  height = NULL,
  dpi = NULL
)

wrap_plots(
  plots,
  ncol = NULL,
  nrow = NULL,
  byrow = TRUE,
  widths = NULL,
  heights = NULL,
  guides = c("collect", "keep"),
  design = NULL,
  width = NULL,
  height = NULL,
  dpi = NULL
)

hconcat(..., guides = c("collect", "keep"), height = NULL)

vconcat(..., guides = c("collect", "keep"), width = NULL)

Arguments

...

PlotSpecs or PlotCompositions to arrange.

ncol, nrow

Grid dimensions for concat() (defaults to roughly square).

byrow

Fill the grid by row (default) or by column.

widths, heights

Relative panel sizes per column / row (recycled numeric vector), or NULL for equal panels.

guides

"collect" (default) to dedupe identical legends across sub-plots into one, or "keep" to leave each sub-plot's legend in place. The collected legend goes where the composition's theme puts it (theme(comp, legend.position = ): "right", the default, "left", "top", "bottom" or "none"), as in patchwork; the sub-plots' own themes do not move it.

design

An explicit layout: a list of area()s (one per plot, in the order plots are passed) or a textual layout string (rows split by ⁠\n⁠, ⁠#⁠ an empty cell). In a string, distinct letters bind to the plots in ... in alphabetical order (the first letter to the first plot), so there must be exactly one letter per plot and every row must be the same width. Enables spanning; NULL (default) uses the regular ncol/nrow grid.

width, height

Output size in inches (defaults scale with the grid).

dpi

Output resolution in dots per inch. NULL (default) inherits the first sub-plot's resolution; overridable at render time via render_plot().

plots

A list of PlotSpecs / PlotCompositions (for wrap_plots()).

Details

Sub-plot panels are aligned across the grid (a shared track grid lines up panel edges even when axis labels differ), and identical legends are collected into one shared legend by default (guides = "collect"). Pass PlotCompositions in ... to nest a sub-grid. Annotate the whole figure with compose_annotation().

Value

A PlotComposition (renders via render_plot() / vellum::render()).

Examples

a <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
b <- vplot(mtcars) |> mark_histogram(x = mpg, bins = 10)
hconcat(a, b)

Conditional encoding: style by selection membership

Description

Use condition() as the value of a mark aesthetic to make that aesthetic depend on whether an element is in a selection: members get if_true, non-members get if_false. This is the general form of highlight-on-interaction.

Usage

condition(selection, if_true, if_false, empty = TRUE)

Arguments

selection

The selection name (a string) that drives the condition.

if_true

The aesthetic value for selection members — a column expression (data-masked) or a constant.

if_false

The value for non-members — a constant, a column expression (data-masked, one value per row), or omitted to use the theme's dim appearance. For color / fill, a column whose values are levels (or, on a continuous scale, numbers) of the aesthetic's scale is taken through that scale, as if_true is; any other value is read as a colour, and a row whose value is neither gets the theme dim. For alpha, a number in ⁠[0, 1]⁠ (constant or per row) is the non-members' opacity.

empty

Whether an empty selection matches all elements (TRUE, default).

Details

condition() is recognised where it appears in a ⁠mark_*()⁠ encoding; calling it directly is an error. The if_true branch is drawn on a static render and trains scales exactly as the equivalent plain encoding, so color = condition("s", g, "grey80") produces the same colour scale and legend as color = g. With empty = TRUE (the default) an empty selection matches everything, so a static / initial render shows if_true for all elements and interaction dims non-members to if_false. A constant if_true (one that refers to no data column, such as alpha = condition("s", 1, 0.2) or color = condition("s", "red", "grey80")) is a setting, as alpha = 1 is: it is drawn at that value and trains no scale and adds no legend.

Value

Used only inside a ⁠mark_*()⁠ encoding; not called directly.

See Also

select_point(), filter_by()


Coordinate systems

Description

coord_cartesian() is the default Cartesian system; pass xlim/ylim to zoom the view (out-of-range marks are clipped, not dropped — unlike a ⁠scale_*(limits=)⁠, which here behaves the same but is the data-scale's job). coord_flip() swaps the x and y axes, e.g. for horizontal bars. coord_fixed() / coord_equal() lock the aspect ratio so one data unit on the y axis occupies ratio times the physical length of one unit on x (the panel shrinks to fit and is centred). Coordinate limits take precedence over scale limits.

Usage

coord_cartesian(plot, xlim = NULL, ylim = NULL)

coord_flip(plot, xlim = NULL, ylim = NULL)

coord_fixed(plot, ratio = 1, xlim = NULL, ylim = NULL)

coord_equal(plot, ratio = 1, xlim = NULL, ylim = NULL)

Arguments

plot

A PlotSpec.

xlim, ylim

Length-2 view-window limits, or NULL to use the trained range.

ratio

Aspect ratio for coord_fixed(): the device length of one y unit relative to one x unit (default 1).

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> coord_cartesian(xlim = c(2, 4))
vplot(mtcars) |> mark_bar(x = factor(cyl)) |> coord_flip()
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> coord_fixed()

Polar coordinates

Description

coord_polar() projects the panel into polar space: one position aesthetic becomes the angle and the other the radius. With theta = "x" (the default) the x aesthetic maps to angle and y to radius — a categorical bar chart becomes a wind-rose / coxcomb, a line becomes a radar/spider trace, a point cloud is positioned by ⁠(angle, radius)⁠. With theta = "y" a stacked bar becomes a pie (see also the mark_pie() / mark_donut() shortcuts). The panel is locked to a square. Lines, areas, and ribbons are interpolated into smooth arcs.

coord_radial() is a fuller polar system (ggplot2 3.5's name): besides theta/start/direction it takes end to sweep only a partial arc (e.g. a half-circle gauge) and inner_radius to open a donut hole. With end = NULL and inner_radius = 0 it is identical to coord_polar().

Usage

coord_polar(plot, theta = "x", start = 0, direction = 1)

coord_radial(
  plot,
  theta = "x",
  start = 0,
  end = NULL,
  direction = 1,
  inner_radius = 0
)

Arguments

plot

A PlotSpec.

theta

Which position aesthetic drives the angle: "x" (default) or "y".

start

Angular offset of the zero position, in radians (0 places the first value at twelve o'clock).

direction

Winding direction: 1 for clockwise (default), -1 for counter-clockwise.

end

Arc end angle in radians; NULL (default) sweeps a full turn from start. Set it for a partial arc — e.g. ⁠start = -pi/2, end = pi/2⁠ for a semicircular gauge.

inner_radius

Radius of the central hole as a fraction of the outer radius (0–1); 0 (default) is a filled disc, ⁠> 0⁠ a donut/ring.

Value

The modified PlotSpec.

See Also

mark_pie(), mark_donut()

Examples

vplot(mtcars) |> mark_bar(x = factor(cyl)) |> coord_polar(theta = "x")
vplot(mtcars) |>
  mark_bar(x = factor(cyl)) |>
  coord_radial(theta = "x", inner_radius = 0.3)

Map coordinate system

Description

coord_sf() is the coordinate system for mark_sf() maps. Before scale training it reprojects every sf layer to a common CRS (via sf::st_transform()), so the renderer only ever sees projected Cartesian coordinates, and it locks the panel aspect ratio so the map is not stretched: 1 for a projected CRS, and the equirectangular correction 1/cos(mean_latitude) for unprojected longitude/latitude data.

Usage

coord_sf(
  plot,
  crs = NULL,
  xlim = NULL,
  ylim = NULL,
  graticule = FALSE,
  graticule_labels = TRUE
)

Arguments

plot

A PlotSpec.

crs

Target coordinate reference system to project all layers into (anything sf::st_crs() accepts, e.g. an EPSG code, "OGC:CRS84", or a proj/WKT string). NULL (default) uses the CRS of the first sf layer. For guaranteed longitude/latitude order, use "OGC:CRS84" rather than EPSG:4326. For choropleths, prefer an equal-area CRS.

xlim, ylim

Length-2 view-window limits in the target CRS, or NULL.

graticule

Draw meridians and parallels behind the map. FALSE (default) draws none; TRUE picks round longitude/latitude breaks automatically; a list list(lon = , lat = ) sets the breaks explicitly (in degrees). For a projected CRS the lines are reprojected and therefore curved; for unprojected longitude/latitude they are straight.

graticule_labels

Label the graticule lines with their degree values (default TRUE); ignored when graticule is FALSE.

Details

sf is an optional dependency (in Suggests); coord_sf() errors with an install hint if it is not available at render time.

Value

The modified PlotSpec.

See Also

mark_sf(), mark_scalebar(), mark_compass()

Examples

## Not run: 
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
vplot(nc) |> mark_sf(fill = BIR74) |> coord_sf(crs = "OGC:CRS84")
vplot(nc) |> mark_sf(fill = BIR74) |> coord_sf(crs = 3857, graticule = TRUE)

## End(Not run)

Transformed coordinate system

Description

coord_trans() applies a nonlinear transform to the display of one or both position axes, after the scale has trained. This differs from a ⁠scale_*(trans=)⁠: a scale transform rescales the data and picks its breaks in the transformed space (so a log scale is labelled ⁠1, 10, 100⁠), whereas coord_trans() keeps the trained breaks at their original data values and only warps where they are drawn — so the axis is still labelled with the raw values, the gridlines bunch up, and straight lines curve. Use it to show data on, say, a log display without relabelling the axis in powers of ten.

Usage

coord_trans(plot, x = "identity", y = "identity")

Arguments

plot

A PlotSpec.

x, y

Display transform for that axis (default "identity").

Details

The transform is separable per axis. Each of x/y is a transform name ("identity", "log10", "sqrt") or a ⁠scales::transform_*()⁠ object. It is intended for continuous position axes; "reverse" is better expressed as scale_*(trans = "reverse").

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> coord_trans(y = "log10")

Set the easing of an animation's frames

Description

ease_aes() chooses the easing function that shapes how the interpolation fraction moves through each transition — e.g. "cubic-in-out" starts and ends gently. By default it applies to every interpolated aesthetic; the position/color/size/alpha arguments override it for one class each, so marks can glide into place on a cubic curve while their colour crossfades evenly.

Usage

ease_aes(
  plot,
  ease = "linear",
  position = NULL,
  color = NULL,
  size = NULL,
  alpha = NULL,
  colour = NULL
)

Arguments

plot

A PlotSpec carrying a transition_states().

ease

An easing name: "linear", or a family (quad/cubic/quart/quint/sine/expo/circ/back/elastic/bounce) with a direction suffix (⁠-in⁠, -out, ⁠-in-out⁠), e.g. "cubic-in-out". Used for any class not given its own easing below.

position, color, size, alpha

Optional per-class easings, named the same way as ease. NULL (the default) means "use ease". Each covers one class of drawn property:

  • position — x and y, and every other coordinate-space quantity (bar widths, angles, path vertices, text rotation). It also decides when discrete attributes flip, since those snap at the halfway point.

  • color — color and fill, including per-element fills.

  • size — size, linewidth, and radii.

  • alpha — opacity, and the fade of marks entering or leaving a state.

position covers x and y together: the engine has a single positional curve, so the two axes cannot be eased apart.

colour

An alias for color; supplying both is an error.

Value

The modified PlotSpec.

See Also

transition_states(), animate()

Examples

# Four bars in every state, so each bar tweens into its next height.
d <- data.frame(t = rep(1:3, each = 4), g = rep(letters[1:4], 3),
                v = c(1, 3, 2, 4, 4, 1, 3, 2, 2, 4, 1, 3))
vplot(d) |>
  mark_bar(x = g, y = v, fill = g) |>
  transition_states(t) |>
  ease_aes("cubic-in-out")

# Bars settle into place gently, but the colour crossfade stays even.
vplot(d) |>
  mark_bar(x = g, y = v, fill = v) |>
  transition_states(t) |>
  ease_aes("cubic-in-out", color = "linear")

Theme elements

Description

Typed building blocks for theme(). Each describes how a family of theme slots is drawn; any property left NULL is inherited from the slot's parent in the theme tree. element_blank() draws nothing.

Usage

element_text(
  family = NULL,
  face = NULL,
  colour = NULL,
  color = NULL,
  size = NULL,
  cex = NULL,
  hjust = NULL,
  vjust = NULL,
  angle = NULL,
  lineheight = NULL,
  margin = NULL
)

element_line(
  colour = NULL,
  color = NULL,
  linewidth = NULL,
  linetype = NULL,
  lineend = NULL,
  sketch = NULL
)

element_rect(
  fill = NULL,
  colour = NULL,
  color = NULL,
  linewidth = NULL,
  linetype = NULL,
  sketch = NULL
)

element_blank()

Arguments

family, face, size, cex, colour, color, hjust, vjust, angle, lineheight, margin

Text properties. color is an alias for colour; size is in points and cex is a relative multiplier on the inherited size; margin is a numeric vector of millimetres (recycled to length 4).

linewidth, linetype, lineend

Line properties.

sketch

For element_line() / element_rect(), a sketch() spec giving that theme element (gridlines, axis lines, ticks, panel/strip/legend backgrounds) a hand-drawn look, NA to force it crisp, or NULL (default) to inherit from its parent element / the plot-wide theme_sketch() default. Text elements are never sketched.

fill

Fill colour (rectangles).

Value

An element object for use in theme().

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  theme(plot.title = element_text(size = 16), panel.grid.minor = element_blank())

Default mark colours of a theme

Description

element_geom() sets the colours a theme gives marks whose colour or fill is neither mapped nor set, as ggplot2's element_geom() does. Pass it as theme(geom = element_geom(...)); dark themes such as theme_cyberpunk() set a light ink so unmapped points, lines and text stay visible.

Usage

element_geom(
  ink = NULL,
  paper = NULL,
  accent = NULL,
  colour = NULL,
  color = NULL,
  fill = NULL
)

Arguments

ink

Foreground colour of marks (default "black").

paper

Background colour marks are mixed against (default "white").

accent

Colour of fitted smooths and contour lines (default "#3366CC").

colour, color

A colour for every unmapped mark stroke, overriding the colour derived from ink / accent. color is an alias for colour.

fill

A fill for every unmapped filled mark, overriding the fill derived from ink / paper.

Details

Each mark's default is derived from these as in ggplot2. Points, lines, text, rules and error bars use ink; filled marks use a mix of ink and paper (bars, histograms and areas col_mix(ink, paper, 0.35), the default light-theme "grey35"); box plot, violin and label backgrounds use paper; fitted smooths and contours use accent. A mapped scale and a constant ⁠color =⁠ / ⁠fill =⁠ on a mark always win.

Value

An element object for the geom slot of theme().

See Also

theme(), theme_cyberpunk()

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  theme(
    plot.background = element_rect(fill = "grey10"),
    panel.background = element_rect(fill = "grey15"),
    geom = element_geom(ink = "grey90", paper = "grey15")
  )

Facet a plot into a grid of panels

Description

facet_wrap() lays panels out in a ribbon wrapped into ncol/nrow; facet_grid() arranges them on a 2-D grid defined by a rows ~ cols formula. Position scales are shared across panels by default (so axes align); pass scales = "free_x", "free_y", or "free" to train them per panel. Colour, size and the other non-position scales are shared too (one legend); resolve_scale(color = "independent") gives each panel its own.

Usage

facet_wrap(
  plot,
  facets,
  ncol = NULL,
  nrow = NULL,
  scales = c("fixed", "free_x", "free_y", "free"),
  labeller = NULL
)

facet_grid(
  plot,
  facets,
  scales = c("fixed", "free_x", "free_y", "free"),
  labeller = NULL
)

Arguments

plot

A PlotSpec.

facets

A faceting formula. For facet_wrap(), one-sided such as ~ cyl (one or more +-separated variables); for facet_grid(), a two-sided rows ~ cols (use . for no faceting on a side).

ncol, nrow

Number of columns/rows for facet_wrap().

scales

One of "fixed" (default), "free_x", "free_y", "free".

labeller

How to label the facet strips: a labeller such as label_both(), label_value() or label_wrap_gen(), a named character vector looking values up (c("4" = "Four")), or a function from values to labels (see as_labeller()). The default, NULL, shows the values, several variables on one side joined by ", ".

Value

The modified PlotSpec.

See Also

labellers

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> facet_wrap(~cyl)
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> facet_grid(am ~ cyl)
vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  facet_grid(am ~ cyl, labeller = label_both)

Filter a view by a selection

Description

Show only the rows in selection, hiding the rest (a display-tier hide, not a re-aggregation). Point a second view's filter_by() at a selection whose gesture lives in a first view and you get cross-filtering: brush one panel, a linked panel redraws to just those rows.

Usage

filter_by(plot, selection)

Arguments

plot

A PlotSpec.

selection

A SelectionSpec, or a selection name string.

Value

The PlotSpec, with the filter registered.

See Also

select_interval(), add_selection()


Neon glow layer effect

Description

A render effect for stroked, point, and text marks, in the spirit of mplcyberpunk: a widened copy of the mark is drawn beneath the crisp original and softened with a real Gaussian blur (vellum's vl_viewport(blur=)), composited additively (a "screen" blend) into a soft neon halo. Pass it to a mark's effects argument, e.g. mark_line(..., effects = list(glow())). Pairs naturally with theme_cyberpunk().

Usage

glow(size = 6, layers = 6L, alpha = 0.12, blend = "screen", color = NULL)

Arguments

size

Halo spread in millimetres: the blur radius (and, for stroked/point marks, how much the copy is widened before blurring).

layers, blend

Retained for compatibility and the neon look: layers scales the halo opacity (it no longer stacks copies – one blurred layer replaces them), and blend (typically "screen"/"lighten") composites the halo.

alpha

Base halo opacity (scaled by layers).

color

Halo colour, or NULL (default) to inherit the mark's own resolved colour — the usual neon look.

Details

The glow is applied per style group, so a colour-mapped multi-series line glows each series in its own hue. It applies to mark_point(), mark_line(), mark_step(), mark_rule(), mark_segment(), mark_edges(), mark_nodes(), mark_edge_bundle(), mark_flow_map(), and text marks (mark_text() / mark_label()); other marks reject it.

Value

A GlowSpec object for a mark's effects list.

See Also

outline(), shadow(), theme_cyberpunk()

Examples

df <- data.frame(x = 1:20, y = cumsum(rnorm(20)))
vplot(df) |>
  mark_line(x = x, y = y, color = "#00e5ff", effects = list(glow())) |>
  theme_cyberpunk()

Gradient fill paints

Description

linear_gradient() and radial_gradient() are vellum::linear_gradient() and vellum::radial_gradient(), re-exported. A gradient is an unscaled value for the fill aesthetic: pass it directly, e.g. mark_area(x = t, y = y, fill = linear_gradient(c("#00e5ff", "#00e5ff00"))), and the filled region (area / ribbon / bar) is painted with the paint as a single grob. Use "transparent" (or an "#RRGGBB00" colour) as a stop to fade out — the "glow fade under a line" look. A gradient cannot be mapped to a data column (it is one paint per region).

Details

Both take colours and optional stops. A linear gradient's x1/y1/x2/y2 (in units, "npc" by default) set its direction; a radial gradient takes cx/cy/r plus the optional focal circle fx/fy/fr. Both also take extend and interpolation ("srgb" default, or "oklab" / "oklch" to blend the stops perceptually — "oklch" additionally preserves chroma by rotating hue). Each returns a vellum_gradient object usable as a fill value. See vellum::linear_gradient() / vellum::radial_gradient() for the full reference.

See Also

glow(), theme_cyberpunk()

Examples

df <- data.frame(x = 1:20, y = cumsum(abs(rnorm(20))))
vplot(df) |>
  mark_area(x = x, y = y, fill = linear_gradient(c("#00e5ff", "#00e5ff00"),
    x1 = 0, y1 = 1, x2 = 0, y2 = 0))

Add a vellumplot sparkline column to a gt table

Description

gt_vsparkline() renders a list-column of numeric vectors as a per-row vsparkline(), embedded as inline SVG in a gt::gt() table — so a gt table (with all of gt's formatting and theming) gains a vellum sparkline column. Needs the gt package, and HTML output (inline SVG is not embedded by gt's LaTeX / Word backends).

Usage

gt_vsparkline(
  gt_object,
  column,
  type = "line",
  ...,
  width = 30,
  height = 8,
  units = "mm"
)

Arguments

gt_object

A gt::gt() object.

column

The list-column to render (bare name or string).

type

Sparkline type: "line" (default), "bar", or "winloss".

...

Further vsparkline() arguments (e.g. color, points).

width, height, units

Sparkline size (default ⁠30 x 8⁠ mm).

Details

The vectors are recovered from the gt object's data in its current row order; apply gt_vsparkline() before any gt row reordering / grouping.

Value

The modified gt object.

See Also

vsparkline(), vtable(), plot_svg()

Examples

## Not run: 
df <- data.frame(metric = c("A", "B"))
df$trend <- list(cumsum(rnorm(20)), cumsum(rnorm(20)))
gt::gt(df) |> gt_vsparkline(trend, type = "line")

## End(Not run)

Axis guide

Description

guide_axis() controls how a position axis draws its tick labels and line: pass it as guides(x = guide_axis(...)) (or y), or as the guide of a position scale (scale_x_continuous(guide = guide_axis(...))). As in ggplot2, it can stagger crowded labels over several rows (n.dodge), rotate them (angle), drop the ones that would overlap (check.overlap), add minor ticks, and cap the axis line at the outermost breaks. The gutter that holds the labels is measured with the dodging and rotation applied, so nothing is clipped. guides(x = "none") draws the axis without labels or ticks.

guide_axis_logticks() draws log10 ticks: long ones at the powers of ten, middle ones at 5 x 10^k and short ones at the other integer multiples (ggplot2's guide_axis_logticks()). Use it on a trans = "log10" axis, or with prescale.base = 10 on an axis whose data are already log10 values.

Usage

guide_axis(
  title = NULL,
  check.overlap = FALSE,
  angle = NULL,
  n.dodge = 1,
  minor.ticks = FALSE,
  cap = "none"
)

guide_axis_logticks(
  long = 2.25,
  mid = 1.5,
  short = 0.75,
  prescale.base = NULL,
  cap = "none",
  title = NULL
)

Arguments

title

The axis title, or NULL to keep the scale's.

check.overlap

If TRUE, leave out labels that would overlap one already drawn, keeping the first, the last and then those in the middle first (ggplot2's priority). Needs the panel's size, so it applies to a plot with a set page size; free facet scales are thinned panel by panel, and fixed-aspect and marginal plots use their laid-out panel size. Polar axes keep every label.

angle

The rotation of the labels in degrees (overrides the theme's axis.text.x/axis.text.y angle), or NULL to keep the theme's. The labels are justified so their ends meet the ticks.

n.dodge

The number of rows (x) or columns (y) to stagger the labels over, so neighbours alternate between them (default 1).

minor.ticks

If TRUE, also draw shorter ticks halfway between the breaks (on a continuous scale).

cap

Cap the axis line (theme element axis.line) at the outermost breaks: "none" (default; the line spans the panel), "both", "upper" or "lower". TRUE / FALSE mean "both" / "none".

long, mid, short

Lengths of the ticks at 10^k, 5 x 10^k and the other multiples, relative to the theme's axis.ticks.length.

prescale.base

The base the data were already log-transformed with (e.g. 10 for log10(x) plotted on a linear axis), or NULL (default) when the axis itself transforms (or the data are on their own scale).

Value

A guide specification for guides() or a scale's guide.

Examples

cars <- data.frame(model = rownames(mtcars), mpg = mtcars$mpg)
vplot(cars) |>
  mark_bar(x = model, y = mpg) |>
  guides(x = guide_axis(n.dodge = 2))

vplot(cars) |>
  mark_bar(x = model, y = mpg) |>
  guides(x = guide_axis(angle = 45))

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  scale_y_continuous(guide = guide_axis(minor.ticks = TRUE)) |>
  theme(axis.line = element_line()) |>
  guides(x = guide_axis(cap = "both"))

Binned legend

Description

guide_bins() draws the legend of a binned scale the way ggplot2's guide_bins() does: one key per bin, stacked edge to edge, with a small axis beside them whose ticks and labels mark the bin boundaries rather than naming each bin as an interval. Use it for scale_size_binned(), scale_alpha_binned() and the binned colour scales (scale_color_binned(), ⁠scale_*_steps()⁠, ⁠scale_*_fermenter()⁠, ...). It follows the legend's direction: keys run top to bottom (smallest first) in a left / right legend and left to right in a top / bottom one.

Usage

guide_bins(
  title = NULL,
  show.limits = FALSE,
  reverse = FALSE,
  axis = TRUE,
  position = NULL
)

Arguments

title

The legend title, or NULL to keep the scale's.

show.limits

Also label the outer limits of the first and last bins (default FALSE: only the boundaries between bins are labelled).

reverse

Reverse the order of the keys.

axis

Draw the axis line and ticks beside the keys (default TRUE).

position

Where this legend goes: "right", "left", "top", "bottom" or "inside" (over the panels, at theme(legend.position.inside = ) / legend.justification), or "panel": beside each facet panel, on the side theme(legend.position = ) names (right by default; inside each panel when the theme puts legends inside) and justified along the panel edge by legend.justification. A scale resolved "independent" across panels (resolve_scale()) draws each panel's legend there by default; a shared scale placed "panel" repeats its legend beside every panel. NULL (default) follows theme(legend.position = ) (and "panel" for an independent scale). A guide's own position overrides the theme for that legend only, as in ggplot2 3.5, so legends can sit on different sides of one plot; legends at one position stack as usual. A legend at the top or bottom is laid out horizontally. theme(legend.position = "none") still hides every legend. Two legends that would merge (one variable, one title) only merge when they share a position.

Details

A bins legend is drawn on its own: it does not merge with another legend of the same variable, and it shows no key for missing values. On a scale that is not binned it is ignored, with a warning, and the scale keeps its usual legend.

Value

A guide specification for guides() or a scale's guide.

See Also

guides(), guide_coloursteps() for a binned colour scale as a segmented bar.

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, size = hp) |>
  scale_size_binned() |>
  guides(size = guide_bins())

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = qsec) |>
  scale_color_binned(n = 4) |>
  guides(color = guide_bins(show.limits = TRUE)) |>
  theme(legend.position = "bottom")

A 2-D legend for a bivariate scale

Description

guide_bivariate() draws a bivariate colour scale as a square grid of swatches: the x variable's classes run left to right along the bottom, the y variable's classes bottom to top up the side, each axis with its title and an arrow pointing towards "more". When the classes come from bi_class(), each axis is labelled with its class breaks at the swatch edges. rotate = TRUE turns the grid 45 degrees into a diamond, low-low at the bottom and high-high at the top. It is the default guide of scale_fill_bivariate(); use it through guides() to retitle the axes or resize the swatches without respelling the scale. Asking for it on a fill that maps a bi_class()-style column makes that scale bivariate.

Usage

guide_bivariate(
  title = NULL,
  xlab = NULL,
  ylab = NULL,
  key.size = NULL,
  labels = TRUE,
  rotate = FALSE,
  position = NULL
)

Arguments

title

A title above the grid, or NULL (default) for none.

xlab, ylab

The axis titles, or NULL to keep the scale's (or the variable names recorded by bi_class()).

key.size

Side of one swatch, in millimetres. NULL (default) uses 1.5 x the theme's legend.key.size, widened to fit the break labels.

labels

Label the swatch edges with the class breaks bi_class() recorded (default TRUE). A scale without recorded breaks (a hand-made class column) has none to show.

rotate

Turn the grid 45 degrees, so the classes read as a diamond with high-high at the top (default FALSE).

position

Where this legend goes: "right", "left", "top", "bottom" or "inside" (over the panels, at theme(legend.position.inside = ) / legend.justification), or "panel": beside each facet panel, on the side theme(legend.position = ) names (right by default; inside each panel when the theme puts legends inside) and justified along the panel edge by legend.justification. A scale resolved "independent" across panels (resolve_scale()) draws each panel's legend there by default; a shared scale placed "panel" repeats its legend beside every panel. NULL (default) follows theme(legend.position = ) (and "panel" for an independent scale). A guide's own position overrides the theme for that legend only, as in ggplot2 3.5, so legends can sit on different sides of one plot; legends at one position stack as usual. A legend at the top or bottom is laid out horizontally. theme(legend.position = "none") still hides every legend. Two legends that would merge (one variable, one title) only merge when they share a position.

Value

A guide specification for guides().

See Also

scale_fill_bivariate()

Other bivariate: bi_class(), bi_pal(), scale_fill_bivariate()

Examples

d <- bi_class(mtcars, hp, wt)
vplot(d) |>
  mark_point(x = hp, y = wt, color = bi_class, size = 2) |>
  guides(color = guide_bivariate(xlab = "More power", ylab = "More weight"))

# the diamond form
vplot(d) |>
  mark_point(x = hp, y = wt, color = bi_class, size = 2) |>
  guides(color = guide_bivariate(rotate = TRUE))

Control a scale's legend

Description

guides() overrides the legend (guide) for one or more aesthetics without respelling the whole ⁠scale_*()⁠. Pass "none" (or guide_none()) to hide a legend, guide_legend() to tweak a keyed legend (reverse the key order, override the title, restyle the keys with override.aes), guide_colourbar() to size, tick and style a continuous colour bar, or guide_coloursteps() to draw a binned colour scale as a segmented bar instead of swatches; guide_bins() draws any binned scale's keys with the bin boundaries on an axis. Applies to the non-position legends (color/fill, size, shape, alpha, linetype); for the position axes, pass guide_axis() (or "none") as x / y.

Usage

guides(plot, ...)

guide_none()

guide_legend(
  title = NULL,
  reverse = FALSE,
  override.aes = NULL,
  nested = FALSE,
  position = NULL
)

guide_colourbar(
  title = NULL,
  barwidth = NULL,
  barheight = NULL,
  ticks = TRUE,
  ticks.colour = "white",
  label.position = NULL,
  n.breaks = NULL,
  reverse = FALSE,
  position = NULL
)

guide_colorbar(
  title = NULL,
  barwidth = NULL,
  barheight = NULL,
  ticks = TRUE,
  ticks.colour = "white",
  label.position = NULL,
  n.breaks = NULL,
  reverse = FALSE,
  position = NULL
)

guide_coloursteps(
  title = NULL,
  barwidth = NULL,
  barheight = NULL,
  ticks = FALSE,
  ticks.colour = "white",
  label.position = NULL,
  reverse = FALSE,
  position = NULL
)

guide_colorsteps(
  title = NULL,
  barwidth = NULL,
  barheight = NULL,
  ticks = FALSE,
  ticks.colour = "white",
  label.position = NULL,
  reverse = FALSE,
  position = NULL
)

Arguments

plot

A PlotSpec.

...

Named by aesthetic, e.g. guides(color = "none", shape = guide_legend(reverse = TRUE)).

title

An axis/legend title override, or NULL to keep the default.

reverse

Reverse the order of the legend keys / the colour bar.

override.aes

A named list of aesthetics to force on the legend keys, independent of the plotted data — the classic "make faint, small points legible in the key" fix. Recognised names: size (mm), alpha, colour/color, fill, shape, and linewidth. For example override.aes = list(size = 5, alpha = 1) draws big, opaque keys over a scatter of tiny translucent points. NULL (default) leaves the keys as drawn from the data.

nested

For a size legend, draw the keys as concentric, bottom-aligned circles (a proportional-symbol / "bubble" legend) with a leader from each circle to its label, instead of stacked rows. Best with a wide size range (e.g. scale_size(range = c(2, 12))) so the circles are large enough to read; ignored by non-size legends. Drawn for a vertical legend (a horizontal one keeps the stacked keys).

position

Where this legend goes: "right", "left", "top", "bottom" or "inside" (over the panels, at theme(legend.position.inside = ) / legend.justification), or "panel": beside each facet panel, on the side theme(legend.position = ) names (right by default; inside each panel when the theme puts legends inside) and justified along the panel edge by legend.justification. A scale resolved "independent" across panels (resolve_scale()) draws each panel's legend there by default; a shared scale placed "panel" repeats its legend beside every panel. NULL (default) follows theme(legend.position = ) (and "panel" for an independent scale). A guide's own position overrides the theme for that legend only, as in ggplot2 3.5, so legends can sit on different sides of one plot; legends at one position stack as usual. A legend at the top or bottom is laid out horizontally. theme(legend.position = "none") still hides every legend. Two legends that would merge (one variable, one title) only merge when they share a position.

barwidth, barheight

The colour bar's own width and height, in millimetres (guide_colourbar()). barheight sets the bar's length on the default vertical bar (and its thickness on a horizontal one); barwidth its thickness (and the bar length on a horizontal legend). NULL auto-sizes.

ticks

Draw the break ticks on the colour bar? (Default TRUE for guide_colourbar(), FALSE for the segmented guide_coloursteps().)

ticks.colour

Colour of the break ticks (default "white").

label.position

Which side of a vertical colour bar the labels sit, "right" (default) or "left".

n.breaks

Roughly how many ticks (and labels) to put on a continuous colour bar — a target, not a promise: the break algorithm prefers round numbers over the bar's range and returns whatever count reads best near the one asked for, so n.breaks = 4 may draw 3 or 5 rather than tick a value like 23.33. NULL (default) keeps the automatic count. An explicit ⁠breaks =⁠ on the scale names the values that get a tick and outranks this; so does ⁠labels =⁠, which is paired with those breaks.

There is deliberately no nbin argument (ggplot2's band count for the gradient). The bar is drawn as one real gradient fill, not a stack of rectangles approximating one, so it has no bands to count; the segmented look is guide_coloursteps() on a binned scale, where the segments are the scale's own bins.

Value

guides(): the modified PlotSpec. guide_none() / guide_legend(): a guide specification for use inside guides().

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl)) |>
  guides(color = "none")

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl)) |>
  guides(color = guide_legend(reverse = TRUE))

# legible keys over faint, tiny points
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl), alpha = 0.15, size = 0.6) |>
  guides(color = guide_legend(override.aes = list(size = 5, alpha = 1)))

# a taller, wider colour bar with left-side labels and no ticks
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = hp) |>
  guides(color = guide_colourbar(
    barwidth = 8, barheight = 60, ticks = FALSE, label.position = "left"
  ))

# about four ticks on the bar instead of the automatic count
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = hp) |>
  guides(color = guide_colourbar(n.breaks = 4))

# a binned colour scale as a segmented bar
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = hp) |>
  scale_color_binned() |>
  guides(color = guide_coloursteps())

# a proportional-symbol (nested-circle) size legend
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, size = hp) |>
  scale_size(range = c(2, 12)) |>
  guides(size = guide_legend(nested = TRUE))

# one legend at the bottom, the other on the (theme's default) right
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl), size = hp) |>
  guides(color = guide_legend(position = "bottom"))

Overlay a plot as an inset

Description

Place plot as an inset over base, positioned by fractional coordinates (0–1) of the chosen reference box. Returns a 1-cell PlotComposition carrying the inset (compose it further or render directly).

Usage

inset(
  base,
  plot,
  left = 0.6,
  bottom = 0.6,
  right = 0.98,
  top = 0.98,
  align_to = c("panel", "plot", "full"),
  on_top = TRUE,
  shadow = NULL
)

Arguments

base

A PlotSpec or PlotComposition to draw underneath.

plot

The PlotSpec to overlay.

left, bottom, right, top

Inset position as fractions (0–1).

align_to

Reference box: "panel", "plot", or "full" (currently the whole base cell).

on_top

Draw the inset above (TRUE) or below the base.

shadow

Optional drop shadow cast by the inset, from vellum::vl_shadow() (e.g. vl_shadow(dx = 2, dy = 3, blur = 6)).

Details

A plot with a locked aspect ratio (coord_fixed(), coord_sf(), coord_polar(), or theme(aspect.ratio =)) is fitted inside the inset box: the box shrinks in one direction to the plot's own shape, keeping the side nearest the edge it sits on (a box in the right half keeps its right edge, one in the top half its top edge), so its background and border hug the panel rather than framing empty bands.

Each inset's viewport is named "inset-<k>" (the k-th inset of the composition), so it can be found with vellum::node_names().

Value

A PlotComposition.

Examples

a <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
b <- vplot(mtcars) |> mark_histogram(x = mpg, bins = 8)
inset(a, b, left = 0.55, bottom = 0.55, right = 0.98, top = 0.98)

Inspect the data behind a clicked element (click-to-source)

Description

Declare that a host should surface the source data rows behind an element when the user clicks (or hovers) it — the "click-to-source" affordance. It is inert on a static render; a host (vellumwidget::as_widget()) reads the compiled scene's provenance (provenance_join() / provenance_payload()) to answer the gesture, and under Shiny reports the clicked element's rows to ⁠input$<id>_source⁠.

Usage

inspect_source(plot, on = c("click", "hover"), values = FALSE)

Arguments

plot

A PlotSpec.

on

The gesture that reveals the source, "click" (default) or "hover".

values

If TRUE, also ship the referenced data rows so the host can display their values (a heavier payload); FALSE (default) ships only row indices.

Details

This is opt-in because the row mapping adds to the widget payload; declaring it on the plot (rather than as a host flag) keeps interactivity a property of the spec.

Value

The PlotSpec, with source inspection registered.

See Also

provenance_payload(), select_point()

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  inspect_source()

The interaction model of a compiled plot

Description

Returns the serialisable declaration block a host needs to enact a plot's declarative interactivity (selections, conditional encodings, filters, and scale-domain binds), or NULL when the plot declares none. This is the plot-level companion to the per-element metadata carried on the compiled scene; vellumwidget::as_widget() reads it to wire gestures to reactions.

Usage

interaction_model(x)

Arguments

x

A PlotSpec or a plot composition.

Value

A named list (selections, conditions, filters, binds, and source when inspect_source() is declared), or NULL if there is no declared interactivity.


Facet strip labellers

Description

Labellers turn facet values into the text of the facet strips. Pass one as the labeller argument of facet_wrap() or facet_grid().

Usage

label_value(labels, multi_line = TRUE)

label_both(labels, multi_line = TRUE, sep = ": ")

label_wrap_gen(width = 25, multi_line = TRUE)

as_labeller(x, default = label_value, multi_line = TRUE)

Arguments

labels

A data frame of facet values, one column per facet variable.

multi_line

Whether each facet variable gets its own line in the strip (TRUE), or all of them share one line (FALSE).

sep

For label_both(), the text between the variable name and the value.

width

For label_wrap_gen(), the maximum number of characters per line.

x

For as_labeller(), a named character vector (a lookup table from value to label), a function from values to labels, or a labeller (returned as is).

default

For as_labeller(), the labeller for values a lookup table does not name.

Details

  • label_value() shows the value itself ("4").

  • label_both() shows the variable name and the value ("cyl: 4").

  • label_wrap_gen() returns a labeller that wraps long values onto several lines of at most width characters.

  • as_labeller() builds a labeller from a lookup table (a named character vector, c("4" = "Four cylinders")) or from a function that takes the values and returns their labels (toupper). Values the lookup table does not name keep the default labeller's text.

A named character vector or a plain function can also be passed straight to ⁠labeller =⁠; it goes through as_labeller().

The declarative labellers (label_value, label_both, label_wrap_gen() and lookup tables over one of those) survive as_spec(); an arbitrary function does not.

A labeller is a function of one argument, labels: a data frame with one character column per facet variable (named after it) and one row per strip. It returns a list of character vectors, one per line of the strip. With several facet variables on one side, multi_line = TRUE puts each variable on its own line of the strip, and multi_line = FALSE joins them into one line, separated by ", ".

Value

label_value() and label_both() return a list of character vectors. label_wrap_gen() and as_labeller() return a labeller function.

See Also

facet_wrap(), facet_grid()

Examples

p <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
p |> facet_wrap(~cyl, labeller = label_both)
p |> facet_grid(am ~ cyl, labeller = label_both)

# a lookup table, for one side or both
p |> facet_wrap(~am, labeller = c(`0` = "automatic", `1` = "manual"))
p |> facet_wrap(~am, labeller = as_labeller(c(`0` = "automatic"), label_both))

# long values wrapped onto several lines
df <- data.frame(
  x = 1:4,
  y = 1:4,
  g = rep(c("a rather long group name", "short"), 2)
)
vplot(df) |>
  mark_point(x = x, y = y) |>
  facet_wrap(~g, labeller = label_wrap_gen(10))

Set plot titles and axis/legend labels

Description

Add plot-level text — a title, subtitle, caption, and tag — and override the titles of individual axes and legends (x, y, color, fill, size). The title, subtitle, and tag are drawn in a band above the panels; the caption in a band below. Repeated labs() calls merge, with later values winning.

Usage

labs(
  plot,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  tag = NULL,
  x = NULL,
  y = NULL,
  color = NULL,
  colour = NULL,
  fill = NULL,
  size = NULL,
  alt = NULL,
  ...
)

Arguments

plot

A PlotSpec.

title, subtitle, caption, tag

Plot-level text (or NULL to leave unset). In an animation, the title, subtitle and caption may embed frame variables such as "{closest_state}" or "{round(frame_time)}" (see Frame variables in animate()).

x, y, size

Axis / legend title overrides for those aesthetics.

color, colour

Colour-scale title override; colour is an alias for color.

fill

Fill-scale title override. color and fill are separate scales, so each takes its own title; give both the same title (and map the same variable) to draw them as one legend.

alt

A text alternative (alt text) describing the plot for screen readers and other assistive technology. Overrides the description vellumplot generates automatically; see plot_alt(). Emitted into the accessible SVG (⁠<desc>⁠) and tagged PDF (Figure Alt) by render_plot().

...

Reserved; passing anything here is an error.

Details

Axis/legend overrides set here are used unless a matching ⁠scale_*(name = )⁠ is also given, which takes precedence. With neither, the title is derived from the mapping.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  labs(title = "Fuel economy", x = "Weight", y = "MPG")

Set scale limits with a shortcut

Description

Convenience wrappers that declare a scale carrying only its limits, instead of spelling out a full ⁠scale_*()⁠. xlim() / ylim() set the position range; lims() sets limits for any named aesthetic. They are shortcuts for scale_*(limits = ...): like there, an explicit range sets the trained (view) window and marks outside it are clipped.

Usage

lims(plot, ...)

xlim(plot, ...)

ylim(plot, ...)

Arguments

plot

A PlotSpec.

...

For xlim()/ylim(), the limits: two numbers xlim(0, 10) (or a length-2 vector) for a continuous axis, or a set of levels xlim("a", "b", "c") for a discrete one. For lims(), named limit vectors, one per aesthetic, e.g. lims(x = c(0, 10), color = c(0, 100)).

Value

The modified PlotSpec.

See Also

scale_x_continuous()

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> xlim(0, 6)
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> lims(x = c(0, 6), y = c(10, 35))

Map decorations

Description

Cartographic furniture for coord_sf() maps. mark_scalebar() draws a segmented distance bar; mark_compass() draws a north arrow. Both are fixed-position decorations pinned to a panel corner (they take no data aesthetics). Graticule lines (meridians and parallels) are added through coord_sf()'s graticule argument, not a mark, so they render behind the map.

Usage

mark_scalebar(
  plot,
  distance = NULL,
  unit = "km",
  position = "bottomleft",
  segments = 4L,
  height = 2.5,
  pad = 4,
  text_size = 7,
  color = NULL,
  fill = NULL,
  data = NULL
)

mark_compass(
  plot,
  position = "topright",
  size = 10,
  pad = 4,
  rotation = 0,
  color = NULL,
  fill = NULL,
  text = TRUE,
  data = NULL
)

Arguments

plot

A PlotSpec.

distance

Bar length in unit. NULL (default) picks a round number near a quarter of the panel width.

unit

Distance unit for the label and distance: "km" (default), "m", "mi", or "ft".

position

Panel corner to anchor the decoration: "bottomleft" (scale bar default), "topright" (compass default), "bottomright", or "topleft" (the abbreviations "bl"/"br"/"tl"/ "tr" also work).

segments

Number of alternating segments in the bar (default 4).

height

Bar thickness, in millimetres.

pad

Inset from the panel edge, in millimetres.

text_size

Label font size (points).

color, fill

Stroke and fill colours. For the scale bar the segments alternate color and fill; for the compass the arrow is fill with a color outline. By default the scale bar alternates the theme's ink and paper colours (black and white, see element_geom()) and the compass is drawn in its ink.

data

Optional layer data (rarely needed – decorations are not data-driven).

size

Glyph height, in millimetres.

rotation

Extra clockwise rotation of the arrow, in degrees (e.g. to point at grid north on a rotated layout).

text

Draw the "N" label above the arrow (default TRUE).

Value

The modified PlotSpec.

See Also

coord_sf(), mark_sf()

Examples

## Not run: 
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
vplot(nc) |>
  mark_sf(fill = BIR74) |>
  coord_sf(crs = 3857, graticule = TRUE) |>
  mark_scalebar() |>
  mark_compass()

## End(Not run)

Reference lines and function curves

Description

mark_abline() draws a sloped reference line y = slope * x + intercept across the panel (the diagonal cousin of mark_rule()'s horizontal/vertical lines). mark_function() draws a curve y = fun(x) sampled over the panel's x range — e.g. a theoretical density over a histogram, or a reference curve over a scatter. Both take no data encodings; they reuse the panel's existing x/y scales, so add them on top of a data layer. Both assume linear axes.

Usage

mark_abline(
  plot,
  ...,
  position = "identity",
  slope = 1,
  intercept = 0,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_function(
  plot,
  ...,
  position = "identity",
  fun,
  n = 101,
  args = list(),
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec.

...

For mark_abline()/mark_function(), styling passed through as constants (e.g. color, linewidth, linetype).

position

Position adjustment; see mark_point(). A mark errors on a position it does not support, naming the ones it does.

slope, intercept

For mark_abline(), the line's slope and intercept (each may be a vector to draw several lines). Defaults 1 and 0.

blend, sketch, data

See mark_point().

fun

For mark_function(), a function (or its name) mapping a numeric x vector to y, e.g. dnorm or ⁠\(x) x^2⁠.

n

For mark_function(), the number of points sampled across the x range. Default 101.

args

For mark_function(), extra arguments passed to fun (e.g. args = list(mean = 5, sd = 2)).

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> mark_abline(slope = -5, intercept = 37)
vplot(data.frame(x = rnorm(200))) |>
  mark_histogram(x = x, y = after_stat(density)) |>
  mark_function(fun = dnorm)

Area, ribbon, and step marks

Description

mark_area() fills the region between a y line and the zero baseline; mark_ribbon() fills between ymin and ymax; mark_step() draws a staircase line. All connect points in x order.

Usage

mark_area(
  plot,
  ...,
  position = "stack",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_ribbon(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_step(
  plot,
  ...,
  position = "identity",
  direction = "hv",
  auto = FALSE,
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x and y for area/step; x, ymin, ymax for ribbon; plus color/fill/alpha. mark_step() also takes linewidth and linetype; a mapped linewidth varies the staircase's width per tread (see scale_linewidth()).

position

For mark_area(), how areas sharing an x combine when fill/color is mapped: "stack" (default) stacks them into a band, "fill" normalises each x to 1, "identity" overlays them from the zero baseline. With no fill mapping all three are equivalent (a single area).

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

direction

For mark_step(), "hv" (horizontal then vertical, default) or "vh".

auto

For mark_point(), mark_line(), mark_step(), mark_segment(), and mark_edges(), when TRUE and the layer has very many rows, automatically render it as a datashaded density raster (see mark_datashade()) instead of individual vector marks: points bin into a density grid (vellum::datashade()), dense lines/steps rasterise as connected polylines (vellum::datashade_lines()), and segments/edges as independent segments (vellum::datashade_segments()). The datashaded line/segment output is dynspread-ed so thin marks stay visible (see the spread argument of mark_datashade()). The fallback is skipped under a warped coordinate system (coord_polar() / coord_trans()), which draws the vector marks instead.

effects

A list of layer render effects applied to the mark at draw time — glow(), outline(), and shadow(). Available on stroked and point marks.

Details

An area or ribbon is drawn as one polygon per series (per group, or per level of a discrete fill/color), and a polygon has a single fill. A continuous fill, color or alpha must therefore be constant within each series; one that varies along a series is an error. A color given alongside a fill outlines the band: an area along its top, a ribbon along both edges. A color alone fills it. With neither, an area or ribbon fills with ggplot2's default, col_mix(ink, paper, 0.2) from the theme's element_geom() ("grey20" on a light theme).

Value

The modified PlotSpec.

See Also

scale_linewidth()

Examples

vplot(pressure) |> mark_area(x = temperature, y = pressure)

Boxplot, error bar, and summary marks

Description

mark_boxplot() draws a box-and-whisker per x category from the raw y values (box = Q1-Q3, median line, 1.5*IQR whiskers, outlier points). mark_errorbar() draws vertical bars from ymin to ymax with horizontal caps; mark_linerange() omits the caps. mark_summary() aggregates y per x with fun (default mean) and draws the result as points; give it fun.data (or fun.min / fun.max) and it draws each summary as a point with a range instead, like ggplot2's stat_summary().

Usage

mark_boxplot(
  plot,
  ...,
  position = "identity",
  orientation = NA,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_errorbar(
  plot,
  ...,
  position = "identity",
  orientation = NA,
  width = NULL,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_linerange(
  plot,
  ...,
  position = "identity",
  orientation = NA,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_summary(
  plot,
  ...,
  position = "identity",
  fun = mean,
  fun.data = NULL,
  fun.min = NULL,
  fun.max = NULL,
  fun.args = list(),
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_pointrange(
  plot,
  ...,
  position = "identity",
  orientation = NA,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_crossbar(
  plot,
  ...,
  position = "identity",
  width = NULL,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y for boxplot/summary; x, ymin, ymax (or y, xmin, xmax) for errorbar/linerange; plus color/fill (and linetype for errorbar/linerange).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

orientation

For mark_boxplot(), NA (default) to infer it from the data (horizontal when y is discrete and x is not), "x" for vertical boxes along a discrete x, or "y" for horizontal boxes along y. For mark_errorbar(), mark_linerange() and mark_pointrange(), NA (default) draws horizontal ranges when the layer maps xmin/xmax and no ymin/ymax (ggplot2's geom_errorbarh()), vertical ones otherwise; "x" / "y" force either.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

width

For mark_errorbar(), the cap width in data units, as for mark_bar(width =) and ggplot2's geom_errorbar(). NULL (default) is 90% of the band (the resolution on a continuous axis), the width of a default bar, so error bars over bars span them. Dodged error bars share it among the groups, as dodged bars do. For mark_crossbar(), the box width, the same way (VP-105).

fun

For mark_summary(), the aggregation function (default mean). With fun.min / fun.max it gives the point of the range.

fun.data

For mark_summary(), a summary giving a point and a range per category: "mean_se" (mean +/- one standard error), "mean_cl_normal" (mean with a t-based confidence interval), "mean_sdl" (mean +/- two standard deviations), "median_hilow" (median with the central 95% of the data), or a function of the values that returns y, ymin and ymax (such as ggplot2's mean_se()). Overrides fun, fun.min and fun.max.

fun.min, fun.max

For mark_summary(), functions giving the bottom and top of each category's range (e.g. ⁠fun.min = min, fun.max = max⁠).

fun.args

For mark_summary(), a list of extra arguments to the summary functions, e.g. list(mult = 2) for "mean_se" or list(conf.int = 0.9) for "mean_cl_normal".

Details

A box plot is vertical when x is the discrete axis. When y is discrete and x continuous (mark_boxplot(x = mpg, y = factor(cyl))) it is drawn horizontally, as in ggplot2; orientation forces either. Error bars and ranges are horizontal when they map xmin/xmax at each y instead: mark_errorbar(y = g, xmin = lo, xmax = hi).

mark_pointrange() draws a point at ⁠(x, y)⁠ with a vertical line from ymin to ymax (an identity mark — supply the summary values yourself, e.g. from a model). mark_crossbar() draws a box spanning ymin..ymax with a horizontal line at y. Both are the identity counterparts of the aggregating mark_interval().

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_boxplot(x = factor(cyl), y = mpg)
# horizontal: the discrete variable on y
vplot(mtcars) |> mark_boxplot(x = mpg, y = factor(cyl))
# mean and standard error per category
vplot(mtcars) |> mark_summary(x = factor(cyl), y = mpg, fun.data = "mean_se")
# horizontal error bars
est <- data.frame(term = c("a", "b", "c"), lo = c(-1, 0.2, 1), hi = c(1, 1.5, 2.4))
vplot(est) |> mark_errorbar(y = term, xmin = lo, xmax = hi, width = 0.3)

2-D density contours

Description

mark_contour() draws iso-density contour lines of a 2-D point cloud (x, y); mark_contour_filled() fills the bands between them. By default the field is a kernel density estimate (needs the MASS package); map a z aesthetic to instead contour a supplied surface over a regular x/y grid. Contours are coloured by level automatically — mark_contour() maps color = after_stat(level), mark_contour_filled() maps fill. Contour tracing is done by the engine (vellum::vl_contour()), so no extra package is needed for the lines; a density field additionally needs MASS.

Usage

mark_contour(
  plot,
  ...,
  position = "identity",
  bins = 10,
  binwidth = NULL,
  breaks = NULL,
  n = 100,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_contour_filled(
  plot,
  ...,
  position = "identity",
  bins = 10,
  binwidth = NULL,
  breaks = NULL,
  n = 100,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y (+ optional z surface, color / fill, linewidth, linetype).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

bins

Target number of contour levels (when neither breaks nor binwidth is given).

binwidth

Spacing between contour levels, or NULL.

breaks

Explicit contour levels, or NULL to derive from bins / binwidth.

n

Density-estimate grid resolution per axis (KDE mode only).

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

Details

As in ggplot2, each filled band is coloured by its lower level, and the lowest band – from the highest break at or below the field's minimum (e.g. 0 for a density) up to the first inner level – covers the whole grid, so the field's low-lying parts are painted rather than left as background.

Value

The modified PlotSpec.

Examples

vplot(faithful) |>
  mark_point(x = eruptions, y = waiting) |>
  mark_contour(x = eruptions, y = waiting)
vplot(faithful) |> mark_contour_filled(x = eruptions, y = waiting)

Count overlapping points

Description

mark_count() collapses coincident ⁠(x, y)⁠ observations to one point sized by how many fall there (ggplot2's geom_count() / stat_sum()) — the honest way to show overplotting on a discrete or rounded grid. size defaults to after_stat(n) (the overlap count); map it to after_stat(prop) for the proportion instead.

Usage

mark_count(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y (+ color/fill to count within groups, and size to override the default after_stat(n)).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

Value

The modified PlotSpec.

Examples

vplot(mpg <- data.frame(cyl = mtcars$cyl, gear = mtcars$gear)) |>
  mark_count(x = cyl, y = gear)

Datashade a large point cloud

Description

For data too dense to draw one marker each (overplotted, up to millions of points), mark_datashade() bins the points into a canvas-sized grid in one pass and colours each cell by density (via vellum::datashade()), drawing a single raster that fills the panel. Cost is decoupled from point count and overplotting.

Usage

mark_datashade(
  plot,
  ...,
  position = "identity",
  width = 400,
  height = 300,
  colors = NULL,
  how = "eq_hist",
  span = NULL,
  clip = NULL,
  spread = NULL,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings; x and y are required. Map color/fill to a discrete variable for categorical (count_cat) shading.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

width, height

Aggregation grid size in cells (output raster pixels).

colors

Two or more colours forming the low-to-high density ramp (plain density shading only; ignored when a color/fill aesthetic is mapped).

how

Density-to-colour mapping (and, categorically, per-cell opacity): "eq_hist" (default), "log", "cbrt", or "linear".

span, clip

Optional density-range clamping passed to vellum::datashade(): span = c(lo, hi) absolute limits, or clip = c(0.01, 0.99) percentiles, so a few extreme cells don't flatten the rest. Both default NULL.

spread

Optional post-aggregation spreading to keep sparse output visible (passed to vellum::datashade()): NULL (default) none — the raw one-pass aggregation; a positive integer dilates each shaded pixel by that radius (vellum::spread()); "auto" picks the radius from the image density (vellum::dynspread()). Datashaded lines/segments (auto = TRUE on mark_line() / mark_segment() etc.) default to "auto" since single-pixel lines otherwise vanish.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

data

Optional layer data frame; overrides the plot data for this layer.

Details

Map a discrete color (or fill) aesthetic to shade categorically (datashader's count_cat): each category is aggregated separately and every cell is coloured by the count-weighted average of the category hues it holds, with opacity from its total density — so you see which category dominates where, and where they mix, with a colour legend. The category hues come from the usual discrete colour scale (so scale_color_manual() etc. apply). Without a mapped colour, cell colour encodes plain density via the colors ramp.

Value

The modified PlotSpec.

Examples

n <- 1e5
d <- data.frame(x = rnorm(n), y = rnorm(n), g = sample(c("a", "b"), n, TRUE))
vplot(d) |> mark_datashade(x = x, y = y)
# categorical: colour by group
vplot(d) |> mark_datashade(x = x, y = y, color = g)

2-D density estimate

Description

mark_density_2d() draws the contour lines of a 2-D kernel density estimate of (x, y) and mark_density_2d_filled() fills the bands between them, with the semantics of ggplot2's geom_density_2d() and geom_density_2d_filled(): the density is MASS::kde2d() on an n x n grid over the data range with bandwidths h (default MASS::bandwidth.nrd() per axis) times adjust, and the levels are ~bins pretty breaks of the density over every group. Unlike mark_contour(), the lines are not coloured by level unless you map color = after_stat(level); the filled bands map fill = after_stat(level). A discrete color/fill (or group) estimates one density per group. Needs the MASS package.

Usage

mark_density_2d(
  plot,
  ...,
  position = "identity",
  contour_var = "density",
  bins = NULL,
  binwidth = NULL,
  breaks = NULL,
  n = 100,
  h = NULL,
  adjust = c(1, 1),
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_density_2d_filled(
  plot,
  ...,
  position = "identity",
  contour_var = "density",
  bins = NULL,
  binwidth = NULL,
  breaks = NULL,
  n = 100,
  h = NULL,
  adjust = c(1, 1),
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y (+ color/fill, group, linewidth, linetype, alpha).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

contour_var

The variable to contour: "density" (default), "ndensity" (density scaled to a maximum of 1 per group) or "count" (density times the number of observations in the group).

bins

Target number of contour levels (when neither breaks nor binwidth is given).

binwidth

Spacing between contour levels, or NULL.

breaks

Explicit contour levels, or NULL to derive from bins / binwidth.

n

Number of grid points per axis.

h

Bandwidth (the standard deviation of the kernel) per axis: a number or a pair; NULL (default) uses MASS::bandwidth.nrd().

adjust

Multiplier(s) for the bandwidth, a number or a pair (default c(1, 1)).

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

Value

The modified PlotSpec.

See Also

mark_contour() to contour a supplied z surface.

Examples

vplot(faithful) |>
  mark_point(x = eruptions, y = waiting) |>
  mark_density_2d(x = eruptions, y = waiting)
vplot(faithful) |> mark_density_2d_filled(x = eruptions, y = waiting)

Distribution marks

Description

Marks that summarise the distribution of a variable. mark_ecdf() draws the empirical cumulative distribution of x as a step; mark_rug() draws marginal ticks at each datum; mark_qq() draws a quantile-quantile plot of a sample against a theoretical distribution, with mark_qq_line() adding the reference line. All respect a mapped color/fill grouping.

Usage

mark_ecdf(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_rug(
  plot,
  ...,
  position = "identity",
  sides = "bl",
  length = 0.03,
  blend = NULL,
  data = NULL
)

mark_qq(
  plot,
  ...,
  position = "identity",
  distribution = "qnorm",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_qq_line(
  plot,
  ...,
  position = "identity",
  distribution = "qnorm",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec.

...

Encodings. mark_ecdf() needs x; mark_qq()/mark_qq_line() need sample; mark_rug() takes x and/or y (+ color, alpha, linewidth, linetype).

position

Position adjustment; see mark_point(). A mark errors on a position it does not support, naming the ones it does.

blend, sketch, data

Standard layer arguments (see mark_point()).

sides

Which edges mark_rug() draws ticks on: any of "b" (bottom), "l" (left), "t" (top), "r" (right); default "bl".

length

Rug tick length as a fraction of the panel (default 0.03).

distribution

Quantile function of the reference distribution for mark_qq() / mark_qq_line() (default stats::qnorm).

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_ecdf(x = mpg)
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> mark_rug()
vplot(mtcars) |> mark_qq(sample = mpg) |> mark_qq_line(sample = mpg)

Group summary regions

Description

Marks that summarise a set of ⁠(x, y)⁠ points (per group, when a color or fill is mapped) as a single enclosing region drawn over the raw points.

Usage

mark_ellipse(
  plot,
  ...,
  position = "identity",
  type = "t",
  level = 0.95,
  segments = 51L,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_hull(
  plot,
  ...,
  position = "identity",
  expand = 0,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y, and optionally color/fill (which also splits the points into per-group regions).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

type

Ellipse type: "t", "norm", or "euclid".

level

Confidence level ("t"/"norm") or circle radius ("euclid").

segments

Number of line segments approximating the ellipse.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

expand

For mark_hull(), a margin to grow each hull outward by, as a fraction of the layer's data range on each axis (e.g. 0.05 = 5% of the width and height), so it encloses the markers it wraps rather than passing through their centres. Every hull grows by the same margin on every side, with rounded corners, whatever its size or shape. 0 (default) is the tight hull.

Details

  • mark_ellipse() draws a covariance ellipse: a t distribution (type = "t", the default, robustly estimated via MASS), a multivariate normal ("norm"), or a Euclidean circle of radius level ("euclid"). The algorithm follows ggplot2's stat_ellipse().

  • mark_hull() draws the convex hull of the points.

Both are unfilled by default (a boundary), matching ggplot2; map or set a fill to shade the region. A region needs at least 3 points per group; smaller groups are skipped with a warning.

Value

The modified PlotSpec.

Examples

vplot(iris) |>
  mark_point(x = Sepal.Length, y = Sepal.Width, color = Species) |>
  mark_ellipse(x = Sepal.Length, y = Sepal.Width, color = Species)
vplot(iris) |>
  mark_point(x = Sepal.Length, y = Sepal.Width, color = Species) |>
  mark_hull(x = Sepal.Length, y = Sepal.Width, color = Species)

Network (graph) marks

Description

Draw a node-link diagram on a PlotSpec from vgraph(). mark_edges() draws the edges (straight lines, batched), mark_nodes() the vertices (points), mark_node_text() the vertex labels, and mark_edge_text() labels on the edges. Draw order is fixed regardless of the order you pipe them: edges under edge labels under nodes under node labels. Edges (and edge labels) default to the edge table (vgraph()'s edge_data), nodes and node labels to the node table; the x/y/xend/yend/label/name columns those tables carry are mapped automatically, so bare mark_edges() |> mark_nodes() just works.

Usage

mark_edges(
  plot,
  ...,
  position = "identity",
  color = NULL,
  linewidth = NULL,
  alpha = NULL,
  linetype = NULL,
  arrow = FALSE,
  routing = c("straight", "elbow"),
  elbow_at = c("mid", "start", "end"),
  elbow_axis = c("auto", "v", "h"),
  gradient = FALSE,
  auto = FALSE,
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_edge_bundle(
  plot,
  ...,
  position = "identity",
  type = c("force", "divided", "stub", "path", "hammer", "mingle"),
  color = NULL,
  linewidth = NULL,
  alpha = NULL,
  linetype = NULL,
  params = list(),
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_flow_map(
  plot,
  ...,
  position = "identity",
  root,
  type = c("spiral", "steiner"),
  weight = NULL,
  width_range = c(0.3, 3),
  color = NULL,
  alpha = NULL,
  params = list(),
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_nodes(
  plot,
  ...,
  position = "identity",
  size = NULL,
  shape = NULL,
  fill = NULL,
  color = NULL,
  alpha = NULL,
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_node_text(
  plot,
  ...,
  position = "identity",
  label = NULL,
  color = NULL,
  size = NULL,
  alpha = NULL,
  dist = 0,
  top_n = NULL,
  by = NULL,
  repel = FALSE,
  box_padding = 1,
  point_padding = 1,
  min_segment_length = 2,
  seed = NULL,
  effects = list(),
  blend = NULL,
  data = NULL
)

mark_edge_text(
  plot,
  ...,
  position = "identity",
  label = NULL,
  color = NULL,
  size = NULL,
  alpha = NULL,
  angle = NULL,
  effects = list(),
  blend = NULL,
  data = NULL
)

mark_node_hull(
  plot,
  ...,
  position = "identity",
  fill = NULL,
  color = NULL,
  alpha = 0.25,
  expand = 0.04,
  data = NULL
)

mark_node_pie(
  plot,
  cols,
  ...,
  position = "identity",
  size = 4,
  inner = 0,
  fill = NULL,
  color = NULL,
  linewidth = 0.5,
  alpha = NA,
  data = NULL
)

Arguments

plot

A PlotSpec, normally from vgraph().

...

Encodings mapping node/edge attributes to aesthetics. Nodes: size, color/fill, shape, alpha. Edges: color, linewidth, linetype, alpha. The position channels are supplied by vgraph() and need not be mapped.

position

Position adjustment; see mark_point(). A mark errors on a position it does not support, naming the ones it does.

linewidth

For mark_edges(), the edge width; a constant or (via scale_edge_width()) a mapped expression such as linewidth = weight. For mark_node_pie(), the wedge border width.

linetype

For mark_edges(), the edge line type; a constant or (via scale_edge_linetype()) a mapped expression.

arrow

For mark_edges(), TRUE to draw a closed arrowhead at each edge's target end (the directed convention), FALSE/NULL for none, or a vellum::vl_arrow() spec for full control (ends, type, length, angle) – e.g. arrow = vellum::vl_arrow(ends = "both", type = "open"). Edges are capped exactly at each endpoint's node boundary (per vertex, at any size/resolution), so the head sits on the node edge; self-loops are drawn as teardrop loops sized to the node, with the head on the node boundary.

routing

For mark_edges(), edge routing: "straight" (default) or "elbow" – orthogonal right-angle steps for tree / DAG / dendrogram layouts (still straight segments, no curvature). Elbows keep node-boundary caps and arrowheads.

elbow_at, elbow_axis

For mark_edges(routing = "elbow"), the corner placement and axis. elbow_at is "mid" (default, an S-bend at the midpoint), or "start" / "end" for the corner at the source / target – "start" gives the dendrogram bracket (siblings share a bar at the parent's level). elbow_axis is "auto" (default, the longer side), "v", or "h" to force which axis the corner steps along.

gradient

For mark_edges(), TRUE to fade each (straight) edge from faint at its source to opaque at its target – a direction cue that needs no arrowhead (igraph's edge.gradient). Ignored with routing = "elbow".

auto

For mark_edges(), TRUE to datashade a large graph's edges as a density raster (vellum::datashade_segments()) once the edge count exceeds the datashade threshold, instead of drawing each edge as a vector segment — the fast, overplotting-honest path for hairballs. The device-space refinements of the vector path (parallel-edge offsets, node-boundary caps, arrowheads, teardrop self-loops) do not apply to the rasterised edges.

blend

Optional blend mode (see mark_point()).

effects

A list of layer render effects (glow(), outline(), shadow()) applied to the mark at draw time. On the text marks (mark_node_text() / mark_edge_text()) only shadow() applies.

sketch

A sketch() spec giving the layer a hand-drawn look, NA/FALSE to force it crisp, or NULL (default) to inherit.

data

Optional layer data; overrides the default table.

type

For mark_edge_bundle(), the bundling algorithm: "force" (default, force-directed / FDEB), "divided" (force-directed with direction-split bundles), "stub" (short stubs at each endpoint), "path" (shortest-path bundling), "hammer" (hammer bundling), or "mingle" (multilevel agglomerative edge bundling). Delegated to edgebundle::edge_bundle(). For mark_flow_map(), the flow-tree layout: "spiral" (default, angle-restricted spiral tree; edgebundle only) or "steiner" (approximate Steiner tree; also needs interp).

params

For mark_edge_bundle(), a named list of extra arguments passed to edgebundle::edge_bundle() for the chosen type (e.g. params = list(compatibility_threshold = 0.8)). For mark_flow_map(), extra arguments for the flow-tree builder – edgebundle::flow_tree() when type = "spiral" (e.g. list(alpha = 30)), edgebundle::tnss_tree() when type = "steiner" (e.g. list(gamma = 0.9)). Empty by default.

root

For mark_flow_map(), the source vertex the flow fans out from: a vertex name (matched against the node table) or a vertex index.

weight

For mark_flow_map(), the per-edge flow volume (a mapped edge column, e.g. weight = migrants). Defaults to the graph's weight edge attribute, or 1 if there is none.

width_range

For mark_flow_map(), the drawn branch width range c(min, max) (in linewidth units) that the computed flow is mapped onto. Default c(0.3, 3). The width is resolved at render inside the panel, so it is a physical width that holds at any figure size.

size, shape

For mark_nodes(), the node size (mm) / shape; a constant or a mapped expression. size is also the label font size for mark_node_text()/mark_edge_text(). For mark_node_pie(), the pie radius in mm: a constant (default 4) or a mapped expression such as size = total, drawn through the size scale (see scale_size()) with a size legend.

fill, color, alpha

Convenience aesthetics; a constant or a mapped expression. For nodes, fill (or color) is the marker colour; for mark_edges(), color/alpha map through the edge scales. For mark_node_pie(), color is the wedge border: NULL (the default) is the theme's paper colour, white on a light theme.

label

For mark_node_text(), the label expression (default the vertex name); for mark_edge_text(), the edge label expression (no default – map an edge attribute, e.g. label = weight).

dist

For mark_node_text(), a radial offset (mm) pushing each label outward from the layout centroid, so labels clear the node markers instead of sitting on them. 0 (default) centres the label on the vertex.

top_n, by

For mark_node_text(), label only the top_n vertices with the largest by (an edge/vertex metric column, e.g. by = degree) – the idiomatic "label just the hubs" filter. NULL (default) labels every vertex.

repel

For mark_node_text(), TRUE to move overlapping labels apart with a force-directed layout (ggrepel-style), drawing a thin leader line back to each vertex. box_padding, point_padding, min_segment_length, and seed tune it exactly as in mark_text().

box_padding, point_padding, min_segment_length, seed

Repel tuning for mark_node_text(repel = TRUE); see mark_text().

angle

For mark_edge_text(), the label rotation: a constant in degrees, or "along" to rotate each label along its edge. NULL (default) draws horizontal labels.

expand

For mark_node_hull(), the margin to grow each hull outward by so it encloses the node markers, as a fraction of the layout's range on each axis (default 0.04). Every hull gets the same rounded margin.

cols

For mark_node_pie(), the compositional columns (a character vector of node-table column names, at least two) whose values size each node's wedges. The column names are the wedge categories: they train the fill scale, so the wedge colours get a legend (title it with labs(fill =)) and scale_fill_manual() / scale_fill_brewer() recolour them. A node made of a single category is drawn as a whole disc.

inner

For mark_node_pie(), the inner-radius fraction: 0 (default) draws a pie, ⁠> 0⁠ a donut (e.g. 0.5).

Details

Edge colour, opacity, and line type train on their own scales (scale_edge_color(), scale_edge_alpha(), scale_edge_linetype(), plus scale_edge_width()), independent of the node colour/alpha/linetype scales – so a plot can map node fill to a discrete community and edge colour to a continuous weight without the two legends colliding.

mark_node_text() has the label-legibility tools a dense graph needs: repel = TRUE nudges overlapping labels apart with leader lines, dist pushes labels radially clear of the node markers, top_n/by label only the hubs, and effects = list(shadow()) drops a shadow behind each label so it stays readable over edges. mark_edge_text() takes the same effects. (Only shadow() applies to text; a glyph outline / glow is not available yet.)

Two more decorations: mark_node_hull() shades communities with a convex hull behind the graph (grouped by a mapped fill, drawn under the edges), and mark_node_pie() replaces node markers with pie / donut glyphs whose wedges come from a set of compositional columns.

mark_edge_bundle() is a drop-in alternative to mark_edges() that routes the edges as bundled curves instead of straight lines, so a hairball collapses into a few legible trunks. It delegates the geometry to the edgebundle package (install it) and draws the returned paths with the edge aesthetics – type picks the algorithm ("force", "divided", "stub", "path", "hammer", "mingle") and params passes tuning through. Bundled edges are faint by default (alpha = 0.3) so overlapping trunks read as density.

mark_flow_map() draws a flow map: a single root fans out to many destinations along smooth, merging branches whose width tracks the flow volume (the Minard / migration-map idiom). It expects a one-to-many (star) graph rooted at root, laid out at fixed coordinates; edge weight drives the flow. type = "spiral" (default, an angle-restricted spiral tree) needs only edgebundle; type = "steiner" (an approximate Steiner tree) additionally needs interp. Branch width is mapped from the computed flow into width_range, and each branch is drawn as one tapering ribbon: where tributaries merge and the flow changes along a branch, the width varies continuously rather than stepping. (That only arises for type = "steiner", whose flow is per-vertex; a spiral tree's flow is constant along each branch.) A ⁠sketch =⁠ flow map falls back to one uniform stroke per branch, since a hand-drawn ribbon would jitter its outline rather than the pen.

In an interactive host (vellumwidget, or a plot with select_neighbours()) each branch is an element with a tooltip naming the root, the vertex it reaches and its flow (or the layer's own tooltip). A branch reaching a vertex the root has an edge to stands for that edge: it links to its two nodes, so hovering a node highlights its flow, and carries the edge as its join. Its key is the edge's key with a flow suffix, so it never collides with the same edge drawn by mark_edges(). A trunk merging several flows links to no nodes.

These are thin over the point / segment / text marks; igraph need not be installed to use them (only vgraph() needs it). mark_edge_bundle() and mark_flow_map() also need the edgebundle package.

Value

The modified PlotSpec.

See Also

vgraph(), scale_edge_width(), scale_edge_color()

Examples

## Not run: 
g <- igraph::make_graph("Zachary")
vgraph(g) |>
  mark_edges(alpha = 0.5) |>
  mark_nodes(size = 4, fill = "steelblue")

## End(Not run)

Uncertainty marks (slab + interval)

Description

Marks for visualising a distribution's shape and its summary intervals together, in the style of the ggdist package — a natural fit for posterior draws or bootstrap samples (one row per draw, grouped by a categorical x).

Usage

mark_halfeye(
  plot,
  ...,
  position = "identity",
  .width = c(0.66, 0.95),
  point = "median",
  adjust = 1,
  scale = 0.9,
  orientation = NA,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_interval(
  plot,
  ...,
  position = "identity",
  .width = c(0.66, 0.95),
  point = "median",
  orientation = NA,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): a categorical x and the sample y (+ color/fill), or a categorical y and the sample x for horizontal intervals.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

.width

Interval probabilities, widest last (default c(0.66, 0.95)).

point

Central summary: "median" (default) or "mean".

adjust

mark_halfeye() density bandwidth multiplier.

scale

Slab width as a fraction of the category band (mark_halfeye()).

orientation

NA (default) to infer it from the data (horizontal when y is discrete and x is not, as in ggplot2), "x" for vertical intervals along a discrete x (the slab to the right of each), or "y" for horizontal intervals along y (the slab above each).

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

Details

  • mark_halfeye() draws, per category, a one-sided density "slab" (a half violin) with a point-interval at its base: the median (or mean) as a point, a thick bar for the inner interval and a thin bar for the outer one.

  • mark_interval() draws the point-interval alone (no slab).

Intervals are equal-tailed quantile intervals at the .width probabilities (widest drawn thinnest). Supply many draws per x (e.g. posterior samples).

Value

The modified PlotSpec.

Examples

set.seed(1)
draws <- data.frame(
  grp = rep(c("a", "b", "c"), each = 400),
  val = rnorm(1200, rep(c(0, 1, 2), each = 400))
)
vplot(draws) |> mark_halfeye(x = grp, y = val)
vplot(draws) |> mark_interval(x = grp, y = val)
# horizontal: the discrete variable on y
vplot(draws) |> mark_halfeye(x = val, y = grp)

Statistical marks

Description

Marks that apply a statistical transform before drawing. mark_histogram() bins a continuous x and draws the per-bin counts as bars. The bin stat computes count, density (each group integrates to 1), ncount and ndensity (scaled to a maximum of 1), and width, for after_stat(). mark_smooth() fits a model of y on x (per group) and draws the fitted line, with a confidence ribbon when se = TRUE.

Usage

mark_histogram(
  plot,
  ...,
  bins = 30,
  binwidth = NULL,
  breaks = NULL,
  boundary = NULL,
  center = NULL,
  closed = c("right", "left"),
  position = "stack",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_freqpoly(
  plot,
  ...,
  bins = 30,
  binwidth = NULL,
  breaks = NULL,
  boundary = NULL,
  center = NULL,
  closed = c("right", "left"),
  position = "identity",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_smooth(
  plot,
  ...,
  position = "identity",
  method = "auto",
  formula = NULL,
  span = 0.75,
  se = TRUE,
  level = 0.95,
  method.args = list(),
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval), e.g. x, y, color/fill.

bins

Number of histogram bins (default 30), used when neither binwidth nor breaks is given. As in ggplot2, the outer bins are centred on the smallest and largest values unless boundary or center is set.

binwidth

Width of each bin, overriding bins.

breaks

A numeric vector of bin edges, overriding bins and binwidth. Bins may have different widths; values outside the edges are not counted.

boundary, center

Where the bins are aligned: boundary is a position that falls on an edge between two bins, center one that falls on a bin's centre (give at most one). Either may lie outside the data. For example ⁠binwidth = 1, boundary = 0⁠ makes bins ⁠(0, 1]⁠, ⁠(1, 2]⁠, .... With neither, bins of a given binwidth are aligned on binwidth / 2.

closed

Which side of each bin is closed: "right" (default, ⁠(a, b]⁠) or "left" (⁠[a, b)⁠). The outermost edges always count.

position

Position adjustment for the histogram bars ("stack", "dodge", "fill").

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

method

Smoothing method: one of "auto", "lm", "loess", "glm", "gam", "rq".

formula

Model formula in terms of x and y (e.g. y ~ poly(x, 2), y ~ s(x) for gam). Defaults to y ~ x (y ~ s(x) for gam).

span

loess neighbourhood size (larger = smoother).

se

Draw a confidence ribbon around the smooth? Ignored for "rq".

level

Confidence level for the ribbon.

method.args

Extra arguments to the fitting function, e.g. list(family = binomial()) for glm, or list(tau = 0.9) for rq.

Details

mark_smooth() supports several methods:

  • "auto" (default) picks "loess" for small groups (< 1000 points) and "gam" for large ones.

  • "lm" / "glm" — linear and generalised linear fits (glm takes a family via method.args, e.g. binomial() for logistic).

  • "loess" — local regression, controlled by span.

  • "gam" — a generalised additive model with a smooth term (default y ~ s(x)); needs the mgcv package.

  • "rq" — quantile regression at a single method.args$tau (default the median); needs the quantreg package and draws the fitted line only (no confidence ribbon). For several quantiles, add one layer per tau.

mark_freqpoly() draws the same bin counts as a line through the bin centres (a frequency polygon), one line per group. Like ggplot2's geom_freqpoly() it adds an empty bin at each end, so each line starts and ends at zero. It takes the same binning arguments as mark_histogram(), and y = after_stat(density) draws densities instead of counts.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_histogram(x = mpg, bins = 10)
# bins of width 2 with an edge at 10: (10, 12], (12, 14], ...
vplot(mtcars) |> mark_histogram(x = mpg, binwidth = 2, boundary = 10)
vplot(mtcars) |> mark_freqpoly(x = mpg, color = factor(cyl), binwidth = 2)
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> mark_smooth(x = wt, y = mpg)
# local regression with a wider neighbourhood
vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  mark_smooth(x = wt, y = mpg, method = "loess", span = 0.9)

Draw images at data points

Description

mark_image() draws a bitmap image (e.g. a flag or logo) at each ⁠(x, y)⁠, replacing the usual point marker. src is a column of local image file paths (per datum) or a single constant path (the same image at every point). Images are sized by size (height in millimetres); each image's native aspect ratio is preserved.

Usage

mark_image(
  plot,
  ...,
  position = "identity",
  src = NULL,
  size = 5,
  nudge_x = 0,
  nudge_y = 0,
  interpolate = TRUE,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y, and src (the image path column).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

src

Image source: a column of file paths (mapped, one per datum) or a single constant path (the same image at every point).

size

Image height in millimetres (constant or mapped); the width follows the image's own aspect ratio. Default 5.

nudge_x, nudge_y

Shift each image by an exact absolute distance in millimetres along the data x / y axis (+x right, +y up on ordinary axes; swapped under coord_flip()). Default 0.

interpolate

Smoothly interpolate when scaling (default TRUE)? FALSE keeps hard pixel edges.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

data

Optional layer data frame; overrides the plot data for this layer.

Details

Reading image files requires the suggested magick package (which decodes PNG, JPEG, SVG, GIF and more); mark_image() errors with an install hint if it is not available.

Value

The modified PlotSpec.

Examples

## Not run: 
d <- data.frame(x = 1:3, y = c(2, 1, 3),
                flag = c("de.png", "fr.png", "it.png"))
vplot(d) |> mark_image(x = x, y = y, src = flag, size = 8)

## End(Not run)

Label the outliers

Description

mark_outlier_label() labels only the outlying points — the extremes, where the story usually is — instead of every datum. It keeps the rows whose y is an outlier (per colour/fill group) and labels just those, repelled apart with the same solver as mark_text(). Layer it over the raw points. A discrete alpha, size or linewidth styles the labels without splitting the groups outliers are judged within.

Usage

mark_outlier_label(
  plot,
  ...,
  position = "identity",
  method = c("iqr", "sd"),
  k = 1.5,
  size = NULL,
  repel = TRUE,
  box_padding = 1,
  min_segment_length = 2,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y, an optional label (what to write on each outlier), and optionally color / fill to detect outliers within each group.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

method

Outlier rule: "iqr" (Tukey's, the default) or "sd".

k

Threshold multiplier — IQR whisker length (default 1.5) or number of standard deviations.

size

Font size in points.

repel

Move overlapping labels apart (force-directed, ggrepel-style), with leader lines to the points? Single cartesian panel only.

box_padding

Extra space (mm) kept around each label box during repulsion.

min_segment_length

Shortest leader line (mm) worth drawing; a label that barely moved gets none.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

data

Optional layer data frame; overrides the plot data for this layer.

Details

The default method = "iqr" flags y outside ⁠[Q1 - k*IQR, Q3 + k*IQR]⁠ (the boxplot whisker rule); method = "sd" flags ⁠|y - mean| > k * sd⁠. Map a label to name each outlier; with none mapped, the outlier's y value is the label.

Value

The modified PlotSpec.

See Also

mark_text(), mark_boxplot()

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  mark_outlier_label(x = wt, y = mpg, label = rownames(mtcars))

Pie and donut charts

Description

Convenience marks for part-of-whole charts. mark_pie() draws a pie: each value becomes a wedge whose angle is its share of the total, coloured by fill. mark_donut() is a pie with a hollow centre (inner_radius, a fraction of the radius). Both are shorthand for a stacked bar projected through coord_polar() with theta = "y", which they set on the plot; they error if the plot already carries a non-polar coordinate.

Usage

mark_pie(
  plot,
  value,
  fill = NULL,
  ...,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_donut(
  plot,
  value,
  fill = NULL,
  inner_radius = 0.5,
  ...,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec.

value

Encoding (tidy-eval) for each slice's magnitude.

fill

Encoding (tidy-eval) for the slice colour. Omit for a single slice.

...

Further constant aesthetics (e.g. alpha).

blend

Optional blend mode for compositing the layer (see mark_point()).

sketch

A sketch() spec giving the layer a hand-drawn look, or NULL (default) to inherit.

data

Optional per-layer data frame.

inner_radius

For mark_donut(), the inner-hole radius as a fraction of the rim (0 is a pie, the default 0.5 a medium donut).

Value

The modified PlotSpec.

See Also

coord_polar()

Examples

df <- data.frame(part = c("a", "b", "c"), n = c(3, 5, 2))
vplot(df) |> mark_pie(value = n, fill = part)
vplot(df) |> mark_donut(value = n, fill = part, inner_radius = 0.6)

Add marks to a plot

Description

Each ⁠mark_*()⁠ appends a drawing layer to a PlotSpec. Encodings are bare column names (or expressions) captured with tidy evaluation, e.g. ⁠x = wt, y = mpg, color = hp⁠. Scalar values (e.g. size = 3, color = "red") are treated as constant aesthetics rather than data mappings.

Usage

mark_point(
  plot,
  ...,
  size = NULL,
  shape = NULL,
  position = "identity",
  auto = FALSE,
  seed = NULL,
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_line(
  plot,
  ...,
  position = "identity",
  window = NULL,
  auto = FALSE,
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_rule(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_bar(
  plot,
  ...,
  position = "stack",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings: named channel expressions such as x, y, color, fill, size, shape, alpha. Stroked marks (line, step, segment, rule, linerange) also take linewidth and linetype. On mark_line(), mark_step() and mark_segment(), linewidth may be mapped as well as set: see scale_linewidth() for the tapered stroke that gives, and when it falls back to per-segment widths. Everywhere else linewidth is a constant. Every mark also takes group, which says which rows form one series without styling them: mark_line(x = t, y = y, group = id) draws one line per id. Without it, as in ggplot2, the interaction of every discrete color, fill, pattern, linetype, shape, alpha, size and linewidth mapping groups; a continuous colour never does, so a line mapped to one stays connected and changes colour along its length. group = 1 makes the whole layer one group.

size, shape

Convenience arguments for the point size (in mm) / shape; may be a constant or a mapped expression. A shape is a built-in marker ("circle", "square", "triangle", "diamond", "plus", "cross", "triangle_down", "star"), its open or bordered variant ("circle open", "circle filled", ...; see scale_shape()), a ggplot2 shape code (shape = 1 is an open circle, 21 a circle filled with fill inside a color outline), or an SVG icon — a path d string or a .svg file — drawn as a crisp vector marker. Use a literal string (or ⁠!!⁠ a variable holding one) for a constant icon, map shape and pass icons to scale_shape(), or map a column of icons with scale_shape_identity(). A bare variable or column of SVG paths is a mapping like any other, and warns.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

auto

For mark_point(), mark_line(), mark_step(), mark_segment(), and mark_edges(), when TRUE and the layer has very many rows, automatically render it as a datashaded density raster (see mark_datashade()) instead of individual vector marks: points bin into a density grid (vellum::datashade()), dense lines/steps rasterise as connected polylines (vellum::datashade_lines()), and segments/edges as independent segments (vellum::datashade_segments()). The datashaded line/segment output is dynspread-ed so thin marks stay visible (see the spread argument of mark_datashade()). The fallback is skipped under a warped coordinate system (coord_polar() / coord_trans()), which draws the vector marks instead.

seed

For mark_point(position = "jitter"), an optional integer seed making the jitter reproducible. The global RNG stream is restored afterwards.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

effects

A list of layer render effects applied to the mark at draw time — glow(), outline(), and shadow(). Available on stroked and point marks.

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

window

For mark_line(), an optional window (rolling / cumulative / offset) transform of y computed per group over rows ordered by x, before the line is drawn. Either an op name ("mean", "sum", "median", "min", "max", "cumsum", "cummean", "cummax", "cummin", "lag", "lead", "rank") or a list list(op=, k=, align=, partial=): k is the window size (rolling; default 7) or shift (lag/lead; default 1), align is "right" (trailing, default), "left", or "center", and partial (default TRUE) computes at the edges from the shorter available window. For example window = list(op = "mean", k = 7) is a 7-point trailing average.

Details

mark_bar() draws bars from a zero baseline. With an explicit y it uses the y values as heights; with no y it counts rows per category (the "count" stat). When color/fill is mapped, grouped bars are stacked by default; use position = "dodge" for side-by-side bars or "fill" to normalise to 1. width sets the bar width in data units, as in ggplot2 (a fraction of the band on a categorical axis, days on a date axis); the default is 90% of the smallest gap between bars. Dodged bars share it. fill fills the bars and a color given alongside it outlines them (⁠fill = "steelblue", color = "white"⁠); a color alone fills them. The count stat computes count and prop, the share of its group (or of the layer, ungrouped), for use with after_stat(), e.g. y = after_stat(prop). density is an older name for prop.

Value

The modified PlotSpec.

Mappings and settings

A mark argument is either a mapping, whose values go through a scale and get a legend, or a setting, drawn as given with no legend:

  • A literal (color = "red", size = 3) is a setting.

  • A bare name that is a column of the layer's data (color = cyl) is a mapping. The layer's data is its own ⁠data =⁠, else the plot's.

  • A bare name that is not a column, and holds a single value in the calling environment, is a setting, like the literal it holds: ⁠ink <- "#f4eee0"; mark_line(color = ink)⁠ draws in that colour with no legend. A non-column name holding a longer vector (one value per row) still maps. The check is made when the plot is drawn, against the data it is drawn with, so a column always wins over a variable of the same name.

  • Any other expression (color = factor(cyl)) is a mapping.

  • I(x) always sets: color = I(ink). !!x injects the value, so it sets too.

  • .env$x always maps an R value (color = .env$label puts label in a one-entry legend titled "label"), and .data$x always reads a column.

The name rule applies to the arguments that train a non-positional scale: color, fill, size, shape, alpha, linewidth, linetype, pattern and the graph ⁠edge_*⁠ channels. Positions, label and the interactivity arguments (tooltip, data_id, ...) keep their meaning.

Interactivity

Any mark accepts reserved, per-row arguments (captured like encodings, via tidy evaluation) that make its elements addressable — and stylable — by an interactive host without changing what a static render draws:

  • data_id — a per-element data key (e.g. data_id = model). Emitted by the SVG backend as data-key on each element and returned by vellum::scene_model(); it is the join key a host uses to map a hover/click back to a datum, and to link the same datum across views.

  • tooltip — per-element tooltip text (a column expression or a constant), surfaced in scene_model() metadata.

  • hover_group — a field grouping elements for linked emphasis (consumed by a host in a later phase).

  • hover_color, selected_color — per-element outline colours applied by the host when the element is hovered / selected (a constant, or mapped from a column so different marks highlight differently). They override the widget-wide theme set by vellumwidget::as_widget(hover_color=, selected_color=).

These are inert for PNG/PDF and for an SVG opened without a JS host: a plot with none of them compiles and renders exactly as before. Declaring any of them without data_id gives the element a default key, so it is still addressable. A default key names the panel, the layer and the row ("p1-1:l2:7": row 7 of layer 2 in the first panel), so it never matches another layer's keys; give two layers the same data_id to link them. They currently apply to stat = "identity" marks (points, bars, tiles, segments, edges, hexbins, sf features, …); aggregating stats (histogram/count/density) drop them, since rows no longer map 1:1 to elements.

How these flow into the vellum scene (the scene_model() element table, the SVG data-key / ⁠data-vellum-*⁠ attributes, and the reserved meta key vocabulary) is described in vellum's "The scene contract" vignette (vignette("scene-contract", package = "vellum")).

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg, color = hp)

# Declare interactivity (inert on a static render):
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)

Polygon and path marks

Description

mark_polygon() draws one filled polygon per group, its vertices in data order (ggplot2's geom_polygon()). A subgroup cuts holes: within a group, each subgroup is a ring, filled with the even-odd rule so an inner ring is a hole. mark_path() connects the observations in the order they appear in the data, unlike mark_line(), which sorts them by x (ggplot2's geom_path()).

Usage

mark_polygon(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_path(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y, group (one polygon / path per group), subgroup (mark_polygon() holes), fill, color, alpha, linewidth, linetype.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

effects

A list of layer render effects applied to the mark at draw time — glow(), outline(), and shadow(). Available on stroked and point marks.

Details

As in ggplot2, fill fills a polygon (default "grey20") and color outlines it (no outline by default); a color given without any fill fills the polygon instead, as it does for the other filled marks.

Value

The modified PlotSpec.

Examples

tri <- data.frame(
  id = rep(c("a", "b"), each = 3),
  x = c(0, 1, 0.5, 2, 3, 2.5),
  y = c(0, 0, 1, 0, 0, 1)
)
vplot(tri) |> mark_polygon(x = x, y = y, group = id, fill = id)

# a square with a square hole
sq <- data.frame(
  x = c(0, 4, 4, 0, 1, 3, 3, 1),
  y = c(0, 0, 4, 4, 1, 1, 3, 3),
  ring = rep(1:2, each = 4)
)
vplot(sq) |> mark_polygon(x = x, y = y, subgroup = ring)

# a path follows the data order
t <- seq(0, 4 * pi, length.out = 200)
vplot(data.frame(x = t * cos(t), y = t * sin(t))) |> mark_path(x = x, y = y)

Quantile regression lines

Description

mark_quantile() fits a quantile regression of y on x per group for each of quantiles and draws the fitted lines (ggplot2's geom_quantile()). The fit is quantreg::rq() of formula (default y ~ x), predicted on 100 points across the group's range of x. Map color = after_stat(factor(quantile)) (or linetype) to tell the lines apart. Needs the quantreg package.

Usage

mark_quantile(
  plot,
  ...,
  quantiles = c(0.25, 0.5, 0.75),
  formula = NULL,
  method.args = list(),
  position = "identity",
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y (+ color, group, linewidth, linetype, alpha).

quantiles

The conditional quantiles to fit (default c(0.25, 0.5, 0.75)).

formula

The model formula in x and y (default y ~ x), e.g. y ~ splines::ns(x, 3) for a curve.

method.args

A list of further arguments to quantreg::rq().

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

effects

A list of layer render effects applied to the mark at draw time — glow(), outline(), and shadow(). Available on stroked and point marks.

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

Value

The modified PlotSpec.

See Also

mark_smooth() with method = "rq" for one quantile with the smoother's options.

Examples

if (requireNamespace("quantreg", quietly = TRUE)) {
  vplot(mtcars) |>
    mark_point(x = disp, y = mpg) |>
    mark_quantile(x = disp, y = mpg)
}

Raincloud plot

Description

mark_raincloud() is a convenience that composes a raincloud: a one-sided density "cloud" (mark_halfeye()) with the raw observations as "rain" below it (mark_point() with sina spread). It is exactly plot |> mark_halfeye(...) |> mark_point(..., position = position_sina()), so any color/fill mapping in ... flows to both layers.

Usage

mark_raincloud(plot, x, y, ..., width = 0.4, alpha = 0.5)

Arguments

plot

A PlotSpec.

x, y

The categorical x and the sample y (tidy-eval).

...

Further shared encodings (e.g. color, fill) forwarded to both the slab and the points.

width

Sina spread of the rain, as a fraction of the band (default 0.4).

alpha

Point opacity for the rain (default 0.5).

Value

The modified PlotSpec.

See Also

mark_halfeye(), position_sina()

Examples

set.seed(1)
d <- data.frame(g = rep(c("a", "b", "c"), each = 100),
                y = rnorm(300, rep(c(0, 1, 2), each = 100)))
vplot(d) |> mark_raincloud(x = g, y = y)

Rectangle mark

Description

mark_rect() draws one rectangle per row, spanning xmin..xmax by ymin..ymax (ggplot2's geom_rect()). Unlike mark_tile() (a centre and a size), it takes the corner bounds, so an infinite bound reaches the panel edge: ⁠xmin = -Inf, xmax = Inf⁠ shades a full-width band. fill fills (default "grey35") and color outlines; a color given without any fill fills the rectangle instead, as for mark_tile(). annotate()⁠("rect", ...)⁠ draws a one-off rectangle.

Usage

mark_rect(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): xmin, xmax, ymin, ymax (+ fill, color, alpha, linewidth, pattern).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

Value

The modified PlotSpec.

Examples

recs <- data.frame(
  start = c(1, 4, 7), end = c(3, 5, 10),
  party = c("A", "B", "A")
)
vplot(recs) |>
  mark_rect(xmin = start, xmax = end, ymin = 0, ymax = 1, fill = party)

Segment, curve and spoke marks

Description

mark_segment() draws a straight line from ⁠(x, y)⁠ to ⁠(xend, yend)⁠ per row. mark_curve() bends that line into an arc (ggplot2's geom_curve()). mark_spoke() draws a segment from ⁠(x, y)⁠ in the direction angle (radians) with length radius, both in data units (ggplot2's geom_spoke()): a vector field.

Usage

mark_segment(
  plot,
  ...,
  position = "identity",
  auto = FALSE,
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_curve(
  plot,
  ...,
  curvature = 0.5,
  angle = 90,
  ncp = 5,
  position = "identity",
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

mark_spoke(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  effects = list(),
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y, xend, yend (+ color, linewidth, linetype, alpha); mark_spoke() takes angle and radius in place of xend, yend. A mapped linewidth gives each segment its own width – see scale_linewidth().

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

auto

For mark_point(), mark_line(), mark_step(), mark_segment(), and mark_edges(), when TRUE and the layer has very many rows, automatically render it as a datashaded density raster (see mark_datashade()) instead of individual vector marks: points bin into a density grid (vellum::datashade()), dense lines/steps rasterise as connected polylines (vellum::datashade_lines()), and segments/edges as independent segments (vellum::datashade_segments()). The datashaded line/segment output is dynspread-ed so thin marks stay visible (see the spread argument of mark_datashade()). The fallback is skipped under a warped coordinate system (coord_polar() / coord_trans()), which draws the vector marks instead.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

effects

A list of layer render effects applied to the mark at draw time — glow(), outline(), and shadow(). Available on stroked and point marks.

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

curvature

For mark_curve(), the amount of bend: 0 is straight, 1 a half circle; negative values bend the other way (ggplot2's convention: positive bends to the right, travelling from start to end).

angle

For mark_curve(), where the apex of the bend sits, in degrees between 0 and 180: 90 (default) is symmetric, smaller values move it towards the start and larger towards the end.

ncp

For mark_curve(), the number of control points (more give a smoother curve; default 5).

Details

A curve bends in the panel's own frame (its x and y spans scaled to the same length), so on a panel that is not square the arc stretches with the panel; ggplot2 bends in device space instead.

Value

The modified PlotSpec.

See Also

scale_linewidth()

Examples

d <- data.frame(x = 1, y = 1, xend = 5, yend = 4)
vplot(d) |> mark_segment(x = x, y = y, xend = xend, yend = yend)
vplot(d) |> mark_curve(x = x, y = y, xend = xend, yend = yend)

# a vector field
g <- expand.grid(x = 1:8, y = 1:8)
g$angle <- atan2(g$y - 4.5, g$x - 4.5)
vplot(g) |> mark_spoke(x = x, y = y, angle = angle, radius = 0.4)

Direct series labels

Description

mark_series_label() labels each colour/fill series at its end (the point with the largest x) with the series name — a legend-free alternative that reads faster on a multi-line chart. Labels are pushed apart with the same repel solver as mark_text(). Map the same x/y/color as the lines; the label text and colour come from the series automatically.

Usage

mark_series_label(
  plot,
  ...,
  position = "identity",
  size = NULL,
  nudge_x = 2,
  repel = TRUE,
  box_padding = 1,
  min_segment_length = 2,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): the same x, y, and color/fill as the series being labelled.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

size

Font size in points.

nudge_x

Rightward offset (mm) so a label clears its line end (default 2). Widen the x range (or coord_cartesian(clip = FALSE)) if labels crowd the panel edge.

repel

Move overlapping labels apart (force-directed, ggrepel-style), with leader lines to the points? Single cartesian panel only.

box_padding

Extra space (mm) kept around each label box during repulsion.

min_segment_length

Shortest leader line (mm) worth drawing; a label that barely moved gets none.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

data

Optional layer data frame; overrides the plot data for this layer.

Value

The modified PlotSpec.

See Also

mark_text()

Examples

d <- data.frame(
  t = rep(1:10, 3), v = c(1:10, (1:10) * 1.5, 10:1),
  s = rep(c("a", "b", "c"), each = 10)
)
# Give the panel a little x-room and drop the now-redundant colour legend.
vplot(d) |>
  mark_line(x = t, y = v, color = s) |>
  mark_series_label(x = t, y = v, color = s) |>
  xlim(1, 12) |>
  guides(color = "none")

Draw simple-feature (sf) geometries

Description

mark_sf() draws the geometry column of an sf object as a map layer: POINT/MULTIPOINT render as points, LINESTRING/MULTILINESTRING as polylines, and POLYGON/MULTIPOLYGON as filled paths (holes cut with the even-odd rule, so ring winding need not be canonical). Coordinates come from the geometry, so there are no x/y encodings; other aesthetics map feature attributes as usual, e.g. fill = AREA for a choropleth. Pair with coord_sf() to reproject and lock the map aspect ratio.

Usage

mark_sf(
  plot,
  ...,
  position = "identity",
  fill = NULL,
  color = NULL,
  alpha = NULL,
  linewidth = NULL,
  size = NULL,
  na_value = "grey80",
  merge = FALSE,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings mapping feature attributes to aesthetics: fill, color, alpha, linewidth, size. A geometry column is not encoded — it is read from the data.

position

Position adjustment; see mark_point(). A mark errors on a position it does not support, naming the ones it does.

fill, color, alpha, linewidth, size

Convenience aesthetic arguments; a constant or a mapped expression.

na_value

Fill colour for features whose mapped fill/color value is NA (drawn as a distinct legend swatch). Default "grey80".

merge

Dissolve adjacent features that share a fill into one region, so the internal borders between same-valued features disappear and each region is a single crisp path (no seam artefacts, and exact in PDF). The union is real boolean geometry via vellum::vl_path_op(). Default FALSE. Ignored when the layer is interactive (merging would drop the per-feature keys).

blend

Optional blend mode (see mark_point()).

sketch

A sketch() spec giving the layer a hand-drawn look, or NULL (default) to inherit.

data

Optional layer data (an sf object); overrides the plot data.

Details

sf is an optional dependency (in Suggests); mark_sf() errors with an install hint if it is not available.

Value

The modified PlotSpec.

See Also

coord_sf(), scale_fill_binned()

Examples

## Not run: 
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
vplot(nc) |> mark_sf(fill = BIR74) |> coord_sf()

## End(Not run)

Label sf features at their interior point

Description

mark_sf_label() draws one text label per sf feature, placed at the feature's interior point (sf::st_point_on_surface(), guaranteed to fall inside each polygon — unlike a centroid, which can land in a bay or a hole). The label points are reprojected through the same coord_sf CRS as mark_sf(), so they always land where the geometry is drawn. Layer it over a mark_sf() choropleth to name the regions; repel = TRUE (the default) pushes crowded labels apart.

Usage

mark_sf_label(
  plot,
  ...,
  position = "identity",
  size = NULL,
  repel = TRUE,
  box_padding = 1,
  min_segment_length = 2,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): the label to draw at each feature, plus an optional color / size. The position comes from the geometry, so x / y are not mapped.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

size

Font size in points.

repel

Move overlapping labels apart (force-directed, ggrepel-style), with leader lines to the points? Single cartesian panel only.

box_padding

Extra space (mm) kept around each label box during repulsion.

min_segment_length

Shortest leader line (mm) worth drawing; a label that barely moved gets none.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

data

An sf data frame (defaults to the plot's). Its geometry supplies the label positions.

Value

The modified PlotSpec.

See Also

mark_sf(), mark_text()

Examples

if (requireNamespace("sf", quietly = TRUE)) {
  nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
  vplot(nc) |>
    mark_sf(fill = AREA) |>
    mark_sf_label(label = NAME, size = 5)
}

Significance brackets

Description

mark_signif() runs a pairwise test between x groups and draws a significance bracket over each comparison with its p-value (or stars) — the ggsignif / ggpubr idiom. Add it on top of a mark_boxplot() / mark_violin(); the brackets stack above the data and the y-axis expands to fit them.

Usage

mark_signif(
  plot,
  ...,
  position = "identity",
  comparisons = NULL,
  method = c("wilcox.test", "t.test"),
  label = c("p", "stars"),
  step = 0.12,
  tip_length = 0.03,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): a categorical x and the numeric y.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

comparisons

A list of length-2 character vectors naming the group pairs to test, e.g. list(c("a", "b"), c("b", "c")). NULL (default) tests each adjacent pair of levels.

method

The two-sample test: "wilcox.test" (default) or "t.test".

label

"p" (default, a formatted p-value) or "stars" (*/⁠**⁠/⁠***⁠/⁠****⁠/ns).

step

Vertical gap between stacked brackets, as a fraction of the data's y range (default 0.12).

tip_length

Bracket down-tick length, as a fraction of the y range (default 0.03).

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

Value

The modified PlotSpec.

Examples

set.seed(1)
d <- data.frame(g = rep(c("a", "b", "c"), each = 30),
                y = c(rnorm(30), rnorm(30, 1), rnorm(30, 0.4)))
vplot(d) |>
  mark_boxplot(x = g, y = y) |>
  mark_signif(x = g, y = y, comparisons = list(c("a", "b"), c("a", "c")))

Text marks

Description

mark_text() draws the label aesthetic as text at each ⁠(x, y)⁠; mark_label() adds a filled rounded background behind each label. size is the font size in points; angle (degrees) may be mapped or constant.

Usage

mark_text(
  plot,
  ...,
  position = "identity",
  size = NULL,
  family = NULL,
  fontface = NULL,
  hjust = "centre",
  vjust = "centre",
  angle = NULL,
  nudge_x = 0,
  nudge_y = 0,
  repel = FALSE,
  box_padding = 1,
  point_padding = 1,
  min_segment_length = 2,
  seed = NULL,
  effects = list(),
  blend = NULL,
  data = NULL
)

mark_label(
  plot,
  ...,
  position = "identity",
  size = NULL,
  family = NULL,
  fontface = NULL,
  hjust = "centre",
  vjust = "centre",
  angle = NULL,
  nudge_x = 0,
  nudge_y = 0,
  fill = NULL,
  repel = FALSE,
  box_padding = 1,
  point_padding = 1,
  min_segment_length = 2,
  seed = NULL,
  effects = list(),
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y, label (+ color, angle).

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

size

Font size in points.

family, fontface

Font family / face ("plain", "bold", "italic", "bold.italic").

hjust, vjust

Horizontal / vertical justification (constant; "left", "centre", "right", "bottom", "top", or numeric in ⁠[0, 1]⁠).

angle

Text rotation in degrees.

nudge_x, nudge_y

Shift each label by an exact absolute distance in millimetres along the data x / y axis (+x right, +y up on ordinary axes; under coord_flip() nudge_x moves vertically and nudge_y horizontally, and on a reversed axis a positive nudge points toward larger values, as in ggplot2), device-resolved so the nudge is constant regardless of scale or panel aspect. Default 0.

repel

Move overlapping labels apart (force-directed, ggrepel-style), with leader lines to the points? Single cartesian panel only.

box_padding

Extra space (mm) kept around each label box during repulsion.

point_padding

Retained for back-compatibility and currently ignored: the repulsion solver is deterministic and pads uniformly.

min_segment_length

Shortest leader line (mm) worth drawing; a label that barely moved gets none.

seed

Retained for back-compatibility and currently a no-op: the repel layout is deterministic, so there is nothing for a seed to vary.

effects

A list of layer render effects applied to the mark at draw time — glow(), outline(), and shadow(). Available on stroked and point marks.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

data

Optional layer data frame; overrides the plot data for this layer.

fill

For mark_label(), the label background: a constant colour, or a mapped encoding (e.g. fill = group) coloured through the fill/colour scale. Default: the theme's paper colour (white; see element_geom()).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

Details

The label for mark_text() may be plain text (embedded newlines ⁠\n⁠ wrap onto stacked lines) or rich vellum::md() labels — map ⁠label = md(<expr>)⁠ for a per-datum styled label (bold/italic/super-/subscript/colour). (Rich labels are not yet supported by mark_label()'s background box.)

Set repel = TRUE to move overlapping labels apart with a force-directed layout (like ggrepel), drawing a thin leader line back to each label's point. Repulsion is resolved exactly against the true rendered panel size, so it does not depend on the data scale. It is currently limited to a single cartesian panel (no facets / composition / polar).

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_text(x = wt, y = mpg, label = rownames(mtcars))
vplot(mtcars) |> mark_point(x = wt, y = mpg) |>
  mark_text(x = wt, y = mpg, label = rownames(mtcars), nudge_y = 2)

Text set along a path

Description

mark_text_path() draws a label that follows a curve — one string per group, its glyphs placed along the group's x/y points (in data order) and rotated to the local tangent. Use it for a label riding a contour, an arc, or a trend line (a direct-labelling alternative to a legend), where mark_text()'s point-anchored, axis-aligned labels do not fit.

Usage

mark_text_path(
  plot,
  ...,
  position = "identity",
  size = NULL,
  family = NULL,
  fontface = NULL,
  hjust = "centre",
  vjust = "centre",
  offset = 0,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y (the path), label (the string), and optionally color / group to split into separate runs.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

size

Font size in points.

family, fontface

Font family and face ("plain", "bold", ...).

hjust

Where the run sits along the path: "left" starts it at the first point, "centre" centres it, "right" ends it at the last point.

vjust

Vertical placement of the glyphs against the baseline.

offset

Perpendicular standoff from the path, in points (positive is to the left of travel), for a label riding just above or below its curve.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

data

Optional layer data frame; overrides the plot data for this layer.

Details

One label is drawn per group. Split groups the usual way — a discrete color (or a distinct label) starts a new run — and the label is taken from the group's first row (it is constant along the path). The points are used in the order they appear in the data: pre-sort if the curve should be traversed in a particular direction. Because glyphs follow the tangent (like SVG textPath), a label on the underside of a closed curve reads upside-down; reverse the path to flip it.

Value

The modified PlotSpec.

Examples

# Traverse the arc left-to-right so the glyphs read upright (a path walked
# right-to-left would set the label upside-down).
t <- seq(pi, 0, length.out = 40)
d <- data.frame(x = cos(t), y = sin(t), lab = "along the arc")
vplot(d) |> mark_text_path(x = x, y = y, label = lab)

Heatmap marks

Description

mark_tile() draws a rectangular tile at each ⁠(x, y)⁠ coloured by fill; mark_raster() draws the same as one raster image (a fast path requiring a complete regular grid). mark_bin2d() bins continuous x/y into a grid and colours each cell by count. mark_density() draws a 1-D kernel density of x as a filled curve. On all of them a color given alongside a fill (or the default count fill of mark_bin2d() / mark_hex()) outlines the shapes; a color alone fills them. Unmapped, tiles, rasters and densities fill with col_mix(ink, paper, 0.2) from the theme's element_geom() ("grey20" on a light theme), the fill of ggplot2's geom_tile() and geom_area(). (ggplot2's geom_density() draws an unfilled outline; mark_density() keeps its filled curve, filled like an area.)

Usage

mark_tile(
  plot,
  ...,
  position = "identity",
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_raster(plot, ..., position = "identity", blend = NULL, data = NULL)

mark_bin2d(
  plot,
  ...,
  position = "identity",
  bins = 30,
  blend = NULL,
  data = NULL
)

mark_density(
  plot,
  ...,
  position = "identity",
  adjust = 1,
  trim = FALSE,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_hex(
  plot,
  ...,
  position = "identity",
  bins = 30,
  blend = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec (from vplot()).

...

Encodings (tidy-eval): x, y, fill for tile/raster; x, y for bin2d; x (+ fill/color) for density. mark_tile() also takes width and height (data units; default the resolution, so tiles abut). On a continuous axis the tiles' edges train the scale, as in ggplot2, so the end tiles are not clipped.

position

Position adjustment: a string — "identity" (default), "nudge", "stack", "fill", "dodge", "dodge2", "jitter", "jitterdodge", "sina" — or a parameterised position object such as position_dodge() or position_stack(). Every mark takes "identity" and "nudge". "stack"/"fill" work on bars, areas, points, text and labels (so a label can sit on its stacked bar); "dodge"/"dodge2" on bars, points, text, labels, error bars, line/point ranges, cross-bars, box plots, violins and slab-intervals (so error bars dodge over dodged bars); "jitter" on points, text and labels; "jitterdodge" and "sina" on points. A position a mark does not support is an error naming the ones it does.

blend

Optional blend mode for compositing this layer against what is already drawn beneath it (the panel and earlier layers), one of the CSS mix-blend-mode names, e.g. "multiply", "screen", "darken". The whole layer composites as one isolated group (not per element).

sketch

A sketch() spec giving this layer a hand-drawn look (wobbly outlines, hachure fills), NA/FALSE to force it crisp (overriding a plot-wide theme_sketch()), or NULL (default) to inherit. Geometry marks accept it; text, raster, hex and datashade marks do not.

data

Optional layer data frame; overrides the plot data for this layer.

bins

Number of bins per axis for mark_bin2d() / hex columns for mark_hex().

adjust

Bandwidth multiplier for mark_density().

trim

For mark_density(), FALSE (default) estimates every group's density over the range of the whole layer's x, as ggplot2 does; TRUE trims each group's curve to the range of its own data. The curve never runs past the data, so the axis is not padded by the kernel's tails.

Details

mark_density() draws its fill at 80% opacity, so a single curve reads lighter and overlapping groups show through each other. An alpha you set or map replaces the 0.8, and an outline (a color beside a fill) stays opaque.

With its count fill turned off (fill = NULL), mark_hex() fills with ggplot2's col_mix(ink, paper, 0.5) ("grey50" on a light theme). On a theme whose panel is that same grey, such as theme_dark(), it uses col_mix(ink, paper, 0.2) ("grey20") instead, so the hexes stay visible. This differs from ggplot2, which draws grey50 hexes on theme_dark()'s grey50 panel.

Value

The modified PlotSpec.

Examples

d <- expand.grid(x = 1:5, y = 1:5)
d$z <- d$x * d$y
vplot(d) |> mark_tile(x = x, y = y, fill = z)

Density-shape marks

Description

Marks that draw a variable's distribution as a filled shape. mark_violin() draws a mirrored kernel density of y per categorical x (like a boxplot's footprint); mark_ridgeline() draws a kernel density of x per categorical y as overlapping ridges. mark_dotplot() bins x and stacks one dot per observation.

Usage

mark_violin(
  plot,
  ...,
  position = "identity",
  adjust = 1,
  trim = TRUE,
  orientation = NA,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_ridgeline(
  plot,
  ...,
  position = "identity",
  adjust = 1,
  height = 1.4,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

mark_dotplot(
  plot,
  ...,
  position = "identity",
  binwidth = NULL,
  blend = NULL,
  sketch = NULL,
  data = NULL
)

Arguments

plot

A PlotSpec.

...

Encodings. mark_violin() needs categorical x and numeric y; mark_ridgeline() needs numeric x and categorical y; mark_dotplot() needs x. A mapped color/fill sets the shape fill.

position

Position adjustment; see mark_point(). A mark errors on a position it does not support, naming the ones it does.

adjust

Kernel-density bandwidth multiplier (violin/ridgeline).

trim

For mark_violin(), TRUE (default, as ggplot2) ends each violin at the smallest and largest value of its data; FALSE lets the kernel's tails run on past them.

orientation

For mark_violin(), NA (default) to infer it from the data (horizontal when y is discrete and x is not, as in ggplot2), "x" for vertical violins along a discrete x, or "y" for horizontal violins along y.

blend, sketch, data

Standard layer arguments (see mark_point()).

height

Ridge height as a multiple of the row band (ridgeline; default 1.4, so adjacent ridges overlap slightly).

binwidth

Dot-plot bin width, or NULL to use ~1/30 of the data range.

Value

The modified PlotSpec.

Examples

df <- data.frame(g = rep(letters[1:3], each = 50), v = rnorm(150))
vplot(df) |> mark_violin(x = g, y = v)
vplot(df) |> mark_violin(x = v, y = g) # horizontal
vplot(df) |> mark_ridgeline(x = v, y = g)
vplot(df) |> mark_dotplot(x = v)

Run the vellumplot MCP server

Description

Starts a Model Context Protocol server on stdio so an agent can generate validated vellumplot specs. It exposes three tools — get_schema, list_fields, and render_spec — that delegate to spec_schema(), spec_fields(), and spec_diagnose() + render_plot(). A render_spec failure returns structured diagnostics (unknown field, compile error) so the agent can repair and retry, rather than a traceback.

Usage

mcp_serve(input = "stdin", output = stdout())

Arguments

input, output

Connections to read requests from / write responses to (defaults: standard input / output).

Details

The server is pure R (newline-delimited JSON-RPC 2.0 over stdio) and needs no Node or SDK. Point an MCP client at it with: ⁠Rscript -e 'vellumplot::mcp_serve()'⁠, or the bundled launcher system.file("mcp/server.R", package = "vellumplot").

Value

Invisibly NULL, when the input stream closes.

See Also

spec_schema(), spec_fields(), vplot_from_spec()


Rich-text labels

Description

md(text) builds a rich-text label from a markdown subset: ⁠**bold**⁠, ⁠*italic*⁠ / ⁠_italic_⁠, ⁠^superscript^⁠, ⁠~subscript~⁠, and a colour span ⁠[text]{#c00}⁠. It is vellum::md(), re-exported. The result can be used anywhere vellumplot draws a title: labs() (title / subtitle / caption / tag / x / y / color) and ⁠scale_*(name = )⁠. Per-element rich labels (in mark_text()) are not yet supported.

Details

text is a length-one markdown string; the result is a vellum_md_label object accepted by vellum::text_grob(). See vellum::md() for the full reference.

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  labs(title = md("**Fuel** economy"), y = md("Efficiency (mi gal^-1^)"))

Motion-trail layer effects

Description

Draw a fading trail of a stroked or point mark: n copies marching off along a direction (x, y), each further out and fainter than the last, composited beneath the crisp original — a speed-blur or animation-still look. motion() defaults to many close, low-opacity copies (a smooth blur streak); echo() defaults to a few wider-spaced, more-opaque copies (discrete ghost repeats). Both build the same effect, differing only in defaults, and apply to the same marks as glow().

Usage

motion(
  x = 3,
  y = 0,
  n = 8L,
  alpha = 0.15,
  decay = 1,
  spread = 0,
  blend = "normal",
  color = NULL
)

echo(
  x = 4,
  y = 0,
  n = 3L,
  alpha = 0.45,
  decay = 1,
  spread = 0,
  blend = "normal",
  color = NULL
)

Arguments

x, y

Trail direction and length in millimetres (+x right, +y up): the offset of the furthest copy. Defaults to a rightward streak.

n

Number of trail copies.

alpha

Opacity of the nearest (strongest) copy; copies fade toward the tail.

decay

Fade exponent shaping the opacity ramp along the trail (higher = faster fade toward the tail; 0 = no fade).

spread

Optional widening, in millimetres, applied progressively toward the tail (0 keeps a constant width).

blend

Blend mode compositing the trail copies (any CSS mix-blend-mode name); "normal" for opaque ghosts.

color

Trail colour, or NULL (default) to inherit the mark's own resolved colour.

Details

The direction is an absolute distance in millimetres (+x right, +y up), resolved device-side via vellum's compound npc + mm unit, so the trail keeps the same physical length and stays isotropic regardless of the panel's size or aspect (as shadow()'s offset does).

Value

A MotionSpec object for a mark's effects list.

See Also

glow(), shadow(), outline()

Examples

df <- data.frame(x = 1:20, y = cumsum(rnorm(20)))
vplot(df) |> mark_line(x = x, y = y, effects = list(motion(x = 4)))

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, size = 4, effects = list(echo(x = 5)))

Outline (halo) layer effect

Description

Draws one opaque, wider copy of a stroked or point mark beneath the crisp original in a contrasting colour, so the mark stays legible over a busy or dark backdrop (the "sticker" look). Applies to the same marks as glow().

Usage

outline(size = 1, color = NULL, alpha = 1)

Arguments

size

Halo width per side, in millimetres.

color

Outline colour. NULL (the default) is the theme's paper colour (element_geom()): white on a light theme, the dark canvas on a dark one such as theme_cyberpunk().

alpha

Outline opacity.

Value

An OutlineSpec object for a mark's effects list.

See Also

glow(), shadow()

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl), size = 3,
    effects = list(outline()))

Crisp vector hatch fill

Description

pattern_hatch() is the vector companion of the tile patterns above: evenly spaced parallel lines produced as real geometry via vellum::vl_hatch() rather than a rasterised tile. Because it is vector, it stays crisp at any magnification and in PDF (no embedded image), which makes it the better redundant, non-colour encoding for accessible and print output — the "fix it" step alongside plot_lint() and render_plot(cvd = ).

Usage

pattern_hatch(
  color = "grey20",
  bg = NA,
  angle = 45,
  spacing = 3,
  linewidth = 0.75
)

Arguments

color

Line colour (any R colour). Default "grey20".

bg

Background fill painted behind the lines, or NA (default) for a transparent field so what is under the shape shows through.

angle

Line orientation in degrees. Any angle is allowed (unlike the tile patterns, vector hatch has no seamless-tiling restriction). Default 45.

spacing

Distance between lines, in millimetres. Default 3.

linewidth

Line width. Default 0.75.

Details

Use it exactly like the other pattern constructors: as a constant fill on a filled mark, or as one of the values of scale_pattern() to map a discrete variable to hatch textures.

Value

A vellum_hatch object, usable as a fill value.

See Also

patterns, scale_pattern(), plot_lint(), vellum::vl_hatch()

Examples

df <- data.frame(g = c("a", "b", "c"), n = c(3, 5, 2))
vplot(df) |> mark_bar(x = g, y = n, fill = pattern_hatch(angle = 30))

Pattern (hatch) fills

Description

Build a tiling pattern to use as a constant fill value on a filled mark, the texture counterpart of linear_gradient(). Distinguishing regions by texture (not only hue) keeps a plot legible in greyscale print and under colour-vision deficiency. Each constructor assembles a small tile and returns a vellum_pattern (via vellum::vl_pattern()); pass it straight to fill:

Usage

pattern_stripe(
  color = "grey20",
  bg = NA,
  angle = 45,
  spacing = 4,
  linewidth = 1,
  units = "mm"
)

pattern_crosshatch(
  color = "grey20",
  bg = NA,
  angle = 45,
  spacing = 4,
  linewidth = 1,
  units = "mm"
)

pattern_grid(
  color = "grey20",
  bg = NA,
  spacing = 4,
  linewidth = 1,
  units = "mm"
)

pattern_dot(color = "grey20", bg = NA, spacing = 4, size = 1.5, units = "mm")

pattern_checker(color = "grey20", bg = NA, size = 4, units = "mm")

Arguments

color

Line/dot colour (any R colour). Default "grey20".

bg

Background fill painted behind the motif, or NA (default) for a transparent tile so whatever is under the shape shows through.

angle

Stripe orientation in degrees, restricted to 0, 45, 90, or 135 (the orientations that tile seamlessly). Other values error.

spacing

Distance between repeats, in units. Default 4.

linewidth

Stripe / grid line width (as elsewhere in the package). Default 1.

units

Length unit for spacing/size: "mm" (default), "in", "pt", "npc", or "native".

size

For pattern_dot(), the dot diameter in units; for pattern_checker(), the square size in units.

Details

vplot(df) |> mark_bar(x = g, y = n, fill = pattern_stripe(angle = 45))

A pattern is an unscaled value, not a data-mapped channel (like a gradient). It applies to any filled mark: bars, areas, ribbons, rects, tiles, boxplots, violins, ridgelines, half-eyes, hulls/ellipses, and sf polygons. To vary the texture by a variable, map the pattern aesthetic instead (a discrete scale).

Patterns render on every backend (PNG, SVG, and — since the tile embeds as an image — PDF). The tile is rasterised at the scene resolution, so at extreme magnification it can soften; at ordinary sizes it is crisp.

Value

A vellum_pattern object, usable as a fill value.

See Also

linear_gradient(), vellum::vl_pattern()

Examples

df <- data.frame(g = c("a", "b", "c"), n = c(3, 5, 2))
vplot(df) |> mark_bar(x = g, y = n, fill = pattern_crosshatch())

Write a multi-page PDF

Description

pdf_pages() writes several plots into one PDF, one plot per page — a report, a slide deck, or one page per facet. It is the multi-page companion of render_plot() (which writes a single page). Pages may differ in size (each plot keeps its own width/height), and the per-page accessibility tags (structure tree + Alt, see the Accessibility article) are written for every page.

Usage

pdf_pages(x, path)

Arguments

x

Either a list of plots (each a PlotSpec, composition, or table) — one page each — or a single faceted PlotSpec, in which case it is split into one page per facet cell (the facet is dropped and the data filtered per page; each page trains its own scales).

path

Output .pdf path.

Details

This is not vellum::pdf_pages(), which it masks when both packages are attached: vellum's takes a list of scenes and can return the PDF as bytes, while this one takes plots, splits a faceted plot into pages, and always writes to path. It draws through vellum's.

Value

path, invisibly.

See Also

render_plot(), render_all()

Examples

p1 <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
p2 <- vplot(mtcars) |> mark_histogram(x = mpg, bins = 8)
f <- tempfile(fileext = ".pdf")
pdf_pages(list(p1, p2), f)

# one page per facet cell:
faceted <- vplot(mtcars) |> mark_point(x = wt, y = mpg) |> facet_wrap(~cyl)
pdf_pages(faceted, tempfile(fileext = ".pdf"))

Text alternative (alt text) for a plot

Description

Returns the description used as the plot's text alternative for assistive technology. If labs() set an explicit alt, that string is returned verbatim; otherwise vellumplot generates a prose summary from the specification — the chart type, what each axis / colour / size encodes, the number of observations, and any faceting.

Usage

plot_alt(x)

Arguments

x

A PlotSpec or a plot composition.

Details

render_plot() (and any compile through vellum::as_vellum_scene()) passes this text to the scene's description, so the exported SVG carries it in ⁠<desc>⁠ (with role="img") and the exported PDF tags the chart as a Figure whose Alt is this text. The plot title (from labs(title=)) becomes the accessible name. See the Accessibility article.

Value

A single string.

See Also

labs(), vellum::describe()

Examples

p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = hp)
plot_alt(p)
plot_alt(labs(p, alt = "Heavier cars get fewer miles per gallon."))

Encode a plot as a data URI

Description

plot_data_uri() renders a plot to a self-contained ⁠data:⁠ URI string — the bytes of the image inlined as base64 — ready to drop into an HTML ⁠<img src>⁠, a Markdown image, an email, or anywhere a URL is expected without a separate file. "svg" (default) inlines the crisp vector SVG; "png" inlines a raster render.

Usage

plot_data_uri(
  plot,
  format = c("svg", "png"),
  width = NULL,
  height = NULL,
  dpi = NULL,
  ...
)

Arguments

plot

A PlotSpec (or any object plot_svg() / render_plot() accepts).

format

"svg" (vector, default) or "png" (raster).

width, height

Optional size override in inches.

dpi

For format = "png", the render resolution.

...

Passed to plot_svg() (svg) or render_plot() (png).

Value

A length-1 character ⁠data:⁠ URI.

See Also

plot_svg(), render_plot()

Examples

uri <- vplot(mtcars) |> mark_point(x = wt, y = mpg) |> plot_data_uri()
substr(uri, 1, 30)

Lint a plot for legibility and accessibility problems

Description

plot_lint() compiles a plot and reports the design problems a static render hides from a green test suite: text too small to read, colour contrast below the WCAG threshold, two palette colours a colour-blind reader cannot tell apart, labels that overlap or fall off the panel, and grammar-level mistakes such as an encoding with a single level or a legend too long to read. It is the "flag it" step of the accessibility workflow — pair it with render_plot(cvd = ) to see a failing palette and scale_pattern() / pattern_hatch() to fix it with a redundant non-colour encoding.

Usage

plot_lint(x, ..., min_text_px = 7, min_contrast = 3)

Arguments

x

A PlotSpec (or anything vellum::as_vellum_scene() accepts).

...

Passed to vellum::vl_lint(): rules, exclude, severity, cvd, min_text_pt, max_overplot and the rest of the thresholds.

min_text_px

Minimum legible text height in pixels (default 7); text below it is flagged.

min_contrast

Minimum acceptable contrast ratio between a mark and its background (default 3, the WCAG AA threshold for graphical objects).

Details

The geometric rules come from the engine's vellum::vl_lint(), which judges them in resolved device pixels. The grammar rules are registered into the same registry by vellumplot, so they are not special: vellum::vl_lint_rules() lists them, ⁠rules =⁠ selects them, and vellum::vl_lint() on a compiled plot reports them too. Findings are returned most-severe first.

Because every finding carries the box it refers to, vellum::vl_lint_overlay() can draw the report onto the plot, and vellum::vl_lint_assert() can fail a test on it.

A composition or table has no single set of trained scales, so it reports the geometric findings only — lint the cells individually for the grammar ones (vellumplot#147).

Value

A data frame (class vellum_lint) with one row per finding: rule, severity ("warning"/"note"), node, a human message, and the device-px box x0/y0/x1/y1 — NA for a grammar finding, which is about a scale and so has no box. Zero rows when the plot is clean.

See Also

render_plot() (⁠cvd =⁠), scale_pattern(), pattern_hatch(), vellum::vl_lint(), vellum::vl_lint_overlay(), vellum::vl_lint_assert()

Examples

# a tiny-text, single-level-scale plot trips the linter
p <- vplot(transform(mtcars, grp = "one group")) |>
  mark_point(x = wt, y = mpg, color = grp) |>
  theme(axis.text = element_text(size = 2))
plot_lint(p)

# the engine's arguments come through, so a project can accept a finding
plot_lint(p, exclude = "scale:color")

A reproducibility manifest for a plot

Description

plot_manifest() returns a small, serializable fingerprint of a plot: a hash of its input data (order- and column-sensitive), the data's shape and column names, a structural hash of the spec, and the number of emitted elements. It is what plot_svg() can embed (with manifest = TRUE) so a figure carries its own provenance, and what plot_verify() recomputes to confirm a figure still matches its data.

Usage

plot_manifest(x)

Arguments

x

A PlotSpec.

Value

A named list: version, data (a hash/nrow/columns record), spec_hash, n_elements, and fonts (the faces the plot resolved to, via vellum::font_pin(), each a path/index/glyphs record). The fonts are what lets plot_verify() tell a font-stack difference apart from a data change — the same pixels are only guaranteed when the same fonts are present.

See Also

plot_verify(), plot_svg(), provenance_join()

Examples

plot_manifest(vplot(mtcars) |> mark_point(x = wt, y = mpg))$data$hash

Inspect the compiled-scene provenance of a plot

Description

Compiles x and returns its provenance table: one record per emitted mark grob, tying each low-level primitive back to the data rows and trained scales that produced it. Each record's id matches the grob's data-vellum-id in the SVG output (and the id column of vellum::scene_model()), so it is a stable join key between the rendered scene and the grammar — the substrate for interactivity, linked views, and accessibility.

Usage

plot_provenance(x)

Arguments

x

A PlotSpec or plot composition.

Details

Each record is a plain, serializable list:

id

stable node id, equal to grob@id / SVG data-vellum-id (join key).

layer

1-based layer index within the (sub-)plot spec.

mark

mark type ("point", "line", …).

kind

"mark" (the core layer) or "effect" (a decorative underlay).

panel

facet panel key ("panel-r-c"), or NA for a single panel.

channels

aesthetic → trained-scale reference (scale, type, domain).

rows

the original input-data row indices this grob draws: rows of the whole source table (not of a facet panel's subset).

source

the table rows refer to: "plot" for the plot's data, or "layer:<i>" for layer i's own ⁠data =⁠.

The rows field is refined per element for marks that map rows one-to-one to drawn elements (points, bars, tiles, segments, lines, areas, ribbons, steps, text, boxplots, sf features, edges); for aggregating marks (histogram, density, smooth, datashade, …) it is the whole layer (in a faceted plot, the panel's rows), since rows no longer map to single elements.

Value

A list of provenance records (see Details). Empty for a plot that emits no mark grobs.

See Also

vellum::scene_model() and the scene-contract vignette in vellum.

Examples

df <- data.frame(wt = mtcars$wt, mpg = mtcars$mpg, model = rownames(mtcars))
p <- vplot(df) |> mark_point(x = wt, y = mpg, data_id = model)
prov <- plot_provenance(p)
prov[[1]]$id

Reserve an empty cell in a composition

Description

Use inside concat() / wrap_plots() (or a design) to leave a gap.

Usage

plot_spacer()

Value

A spacer placeholder.

Examples

a <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
concat(a, plot_spacer(), a, plot_spacer(), ncol = 2)

Render a plot to a self-contained SVG string

Description

plot_svg() compiles any vellumplot object (a PlotSpec, vtable(), or a composition) to a stand-alone ⁠<svg>⁠ string rather than a file — the way to embed a chart inline in HTML: a vsparkline() in a gt / reactable / DT cell, a chart in a Quarto callout, or an inline glyph in a report. The string carries a viewBox, so it scales.

Usage

plot_svg(
  plot,
  width = NULL,
  height = NULL,
  scaling = c("fixed", "fit"),
  inline = FALSE,
  recolor = NULL,
  text = "native",
  manifest = FALSE
)

Arguments

plot

A PlotSpec, vtable(), or composition.

width, height

Optional page-size override in inches (defaults to the object's own size).

scaling

"fixed" (default) keeps the pixel size; "fit" sets the root ⁠<svg>⁠ width/height to ⁠100%⁠ so it fills its container (the viewBox preserves the aspect).

inline

TRUE strips the leading ⁠<?xml …?>⁠ prolog so the ⁠<svg>⁠ is a valid fragment to drop straight into an HTML paragraph / cell / Quarto inline expression. FALSE (default) keeps the stand-alone-file prolog.

recolor

Optional named character vector mapping a source colour to a replacement written verbatim into the SVG — e.g. c(grey30 = "currentColor") makes a grey30 sparkline follow the surrounding text colour (dark-mode-adaptive inline). Each name is resolved to its hex and swapped for the value; use for CSS keywords ("currentColor") or var(--x) that R's colour engine can't emit itself.

text

How glyphs are emitted: "native" (default) or "outline" (paths, for maximum portability).

manifest

If TRUE, embed a reproducibility manifest (see plot_manifest()) as an XML comment in the SVG, so the figure carries its own data fingerprint; plot_verify() reads it back. Default FALSE.

Value

A length-1 character SVG string.

See Also

vsparkline(), gt_vsparkline(), render_plot(), plot_manifest()

Examples

svg <- plot_svg(vsparkline(cumsum(rnorm(20))))
substr(svg, 1, 40)
# a transparent, prolog-free, dark-mode-adaptive inline sparkline:
plot_svg(vsparkline(1:9, color = "grey30"),
  inline = TRUE, recolor = c(grey30 = "currentColor")
)

Verify a rendered figure against its data

Description

plot_verify() extracts the manifest embedded in an SVG written with plot_svg()(manifest = TRUE) and recomputes the data fingerprint from data, reporting whether the figure still matches the data it was drawn from — a lightweight, self-contained reproducibility check.

Usage

plot_verify(svg, data)

Arguments

svg

An SVG string (from plot_svg()) or a path to an .svg file.

data

The data frame to check the figure against.

Details

A font mismatch is reported as a distinct outcome from a data mismatch: data_ok is whether the data still hashes the same, fonts_ok whether every font the figure was drawn with is still present on this machine, and ok their conjunction. A pixel difference with data_ok = TRUE but fonts_ok = FALSE is the font stack, not your data — a different cause with a different fix (install/register the font) than a data change.

Value

A list with ok (data and fonts match), data_ok, expected / actual (the embedded vs recomputed data hash), fonts_ok, and fonts_missing (the recorded font paths absent on this machine). Errors if the SVG carries no manifest.

See Also

plot_manifest(), plot_svg()

Examples

svg <- plot_svg(vplot(mtcars) |> mark_point(x = wt, y = mpg), manifest = TRUE)
plot_verify(svg, mtcars)$ok

The plot specification

Description

PlotSpec is the S7 class that vplot() creates and the ⁠mark_*()⁠ / ⁠scale_*()⁠ functions extend. It is a plain, inspectable, serializable data object: data, a list of layers, a list of scale overrides, and the page size. Nothing is drawn until it is compiled with vellum::as_vellum_scene() (e.g. via render_plot()). Printing it draws the plot; inspect its structure with base::summary().

Usage

PlotSpec(
  data = NULL,
  edge_data = NULL,
  layers = list(),
  scales = list(),
  facet = NULL,
  coord = NULL,
  resolve = list(),
  width = 6,
  height = 4,
  dpi = 96,
  theme = NULL,
  labels = list(),
  marginal = NULL,
  selections = list(),
  filters = list(),
  binds = list(),
  clip = NULL,
  transition = NULL,
  ease = NULL,
  source = NULL
)

Arguments

data

The data frame.

edge_data

For a graph plot (from vgraph()), the edge table; the default data for mark_edges(). NULL for ordinary plots.

layers

A list of layer specifications (one per ⁠mark_*()⁠).

scales

A list of declared scale overrides.

facet

A faceting specification (from facet_wrap() / facet_grid()), or NULL for a single panel.

coord

A coordinate specification (from coord_cartesian() / coord_flip() / coord_fixed()), or NULL for the default Cartesian system.

resolve

A named list mapping an aesthetic to "shared" or "independent" (the scale-resolution lattice; see resolve_scale()).

width, height

Page size in inches.

dpi

Output resolution in dots per inch (pixels per inch). The exported PNG's pixel dimensions are width * dpi by height * dpi.

theme

A theme (a named list of resolved element/setting overrides, from theme() / a ⁠theme_*()⁠ preset), or NULL for the default theme.

labels

A named list of plot/axis/legend label overrides (see labs()).

marginal

A marginal-distribution specification (from add_marginal()), or NULL for no marginals.

selections

A list of interactive selection declarations (from select_point() / select_interval() / add_selection()).

filters

A list of filter declarations (from filter_by()).

binds

A list of scale-domain bind declarations (from bind_scale()).

clip

A clip_to() / set_mask() geometry clip (a ClipSpec), or NULL for none.

transition

A keyframe-animation transition (from transition_states() / transition_time() / transition_reveal()), or NULL. Read only by animate(); inert on a static render.

ease

An animation easing (from ease_aes()), or NULL.

source

A source-inspection declaration (from inspect_source()), or NULL. Inert on a static render; a host surfaces the data rows behind a clicked element.

Value

A PlotSpec.

See Also

vplot(), mark_point(), scale_x_continuous()


Position adjustments

Description

Fine-grained control over how a mark's overlapping elements are placed. Pass the result to a mark's position argument (e.g. mark_point(position = position_jitter(width = 0.2))). A bare string (position = "dodge") still works and uses the defaults.

Usage

position_nudge(x = 0, y = 0)

position_jitter(width = NULL, height = NULL, seed = NULL)

position_dodge(width = NULL, preserve = c("total", "single"))

position_dodge2(padding = 0.1)

position_stack(vjust = 1)

position_fill(vjust = 1)

position_sina(width = 0.8, seed = NULL)

position_jitterdodge(
  jitter.width = NULL,
  jitter.height = 0,
  dodge.width = 0.75,
  seed = NULL
)

Arguments

x, y

position_nudge() shift (data units).

width, height

Maximum jitter (data units); NULL uses the default. For position_sina(), width is the spread as a fraction of the band.

seed

Optional integer seed for the random jitter.

preserve

position_dodge(): "total" splits the dodge width between the groups present at each x; "single" gives each element the width of one group at the x with the most groups, counted over the whole layer (every facet panel), as in ggplot2.

padding

position_dodge2() gap between dodged elements, as a fraction of the element width.

vjust

position_stack() / position_fill(): where a point, text or label sits inside its stacked span, from 0 (bottom) to 1 (top).

dodge.width, jitter.width, jitter.height

position_jitterdodge() dodge / jitter extents.

Details

  • position_nudge() shifts every element by a constant amount in data units (for continuous axes) — handy for offsetting labels from points.

  • position_jitter() adds uniform random noise; width/height are the maximum shift in data units (default: 40% of the resolution), seed makes it reproducible.

  • position_dodge() places grouped elements side by side; width is the total data-space width shared by the groups at one x (default: the bar width, 90% of the category band). As in ggplot2, only the groups present at an x share it: with preserve = "total" (the default) an x with fewer groups gets wider elements, while preserve = "single" keeps every element as wide as one group at the fullest x.

  • position_dodge2() dodges by the groups actually present at each x and splits the band between them with a padding gap — so ragged groupings stay centred and evenly spaced.

  • position_jitterdodge() dodges grouped elements, then jitters within each dodged slot (points over dodged boxes). As in ggplot2, the default jitter.width is 40% of the resolution divided by (the most groups at any x, over every facet panel, + 2), and there is no vertical jitter.

  • position_stack() / position_fill() stack grouped elements sharing an x (fill normalises each stack to 1). Bars and areas take the stacked span; a point, text or label moves to a height inside its span: vjust = 1 (the default) is the top, 0.5 the middle – so mark_text(position = position_stack(vjust = 0.5)) centres labels on the segments of a stacked bar.

  • position_sina() spreads each category's points along x by a quasirandom offset scaled to the local y-density, so the cloud traces the distribution's shape (ggforce's sina). width is the maximum spread as a fraction of the category band (default 0.8).

Value

A vellumplot_position object for a mark's position argument.

Examples

vplot(mtcars) |>
  mark_point(x = factor(cyl), y = mpg, position = position_jitter(width = 0.15))

Join a plot's provenance to its rendered geometry

Description

provenance_join() compiles x once and returns a tidy table with one row per emitted mark element, tying each drawn primitive to both the source data rows that produced it (rows, a list column) and its device-pixel geometry (x0, y0, x1, y1, x, y, w, h) from vellum::scene_model(). It is the consumer of the provenance table that plot_provenance() emits — the substrate for click-to-source interactivity, auditing "which rows made this element?", and linked views.

Usage

provenance_join(x)

Arguments

x

A PlotSpec or composition.

Value

A data frame: id, layer, mark, kind, panel, source (the table rows refer to, see plot_provenance()), the pixel bbox (x0, y0, x1, y1, x, y, w, h), n_rows, and rows (a list column of integer source-row indices). Empty for a plot with no mark grobs.

See Also

plot_provenance(), vellum::scene_model()

Examples

df <- data.frame(wt = mtcars$wt, mpg = mtcars$mpg, cyl = factor(mtcars$cyl))
p <- vplot(df) |> mark_point(x = wt, y = mpg, color = cyl)
pj <- provenance_join(p)
pj[, c("id", "mark", "n_rows")]

A widget-ready provenance payload (click-to-source)

Description

provenance_payload() returns a JSON-serializable structure mapping each rendered element's stable id (data-vellum-id, the join key an SVG / widget carries) to the source data rows that produced it — the enabler for a host (e.g. vellumwidget) to answer "which rows made this element?" on click, without re-running the grammar. With values = TRUE the referenced data rows are inlined so the host can display them directly.

Usage

provenance_payload(x, values = FALSE)

Arguments

x

A PlotSpec or composition.

values

If TRUE, inline the source data rows (row-wise records) so the host needs no separate data access. Default FALSE (ids + row indices only).

Details

Row indices are 1-based and refer to the table named by the element's source: "plot" for the plot's data, or "layer:<i>" for the data passed to layer i's own ⁠data =⁠ argument. In a faceted plot they are rows of that whole table, not of the panel's subset.

Value

A list with

fields

the plot data's column names.

elements

a list of list(id, rows, source) records.

sources

for a PlotSpec, one record per table an element's rows refer to, named by source: list(fields), plus data (row-wise records) when values = TRUE.

data

when values = TRUE, row-wise records of the plot's data (the "plot" source, kept at the top level for existing hosts).

See Also

provenance_join(), plot_provenance()

Examples

p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = factor(cyl))
pl <- provenance_payload(p)
pl$elements[[1]]$id
pl$elements[[1]]$source

Relative sizing

Description

rel() gives a theme element size as a multiple of the size it inherits, as in ggplot2. theme(axis.text = element_text(size = rel(0.8))) draws the axis text at 80% of the base text size, so it follows a later theme(text = element_text(size = ...)) or a preset's base_size.

Usage

rel(x)

Arguments

x

A single positive number, the multiplier.

Details

A rel() size is resolved against the parent element in the theme tree (text -> axis.text -> axis.text.x and so on). Set on a slot that already holds an absolute size, such as the text root, it scales that size instead: theme(text = element_text(size = rel(2))) doubles every text size.

Value

A number of class rel, for the size of element_text().

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  theme(axis.text = element_text(size = rel(1.2)))

Render many plots to separate files, in parallel

Description

render_all() renders a list of independent plots to separate files across CPU cores — small multiples, a batch export, one file per group. The work is embarrassingly parallel (one whole plot per worker), and the result is byte-identical to rendering them one by one. Parallelism uses process forks, so it speeds things up on macOS/Linux and falls back to sequential on Windows; it is only worth it for several substantial plots.

Usage

render_all(plots, paths, workers = NULL, ...)

Arguments

plots

A named or unnamed list of plots.

paths

Output paths, one per plot (the format of each comes from its extension, as in render_plot()). As a shortcut, when plots is named paths may be a single existing directory, and each plot is written to ⁠<name>.png⁠ inside it.

workers

Number of parallel workers; NULL (default) uses the available cores. 1 forces sequential.

...

Passed to each vellum::render() (e.g. text, cvd).

Details

This wraps vellum::render_all(), which it masks when both packages are attached. It takes plots rather than scenes and checks that every entry is a vellumplot plot before rendering; vellum's accepts anything vellum::as_vellum_scene() can convert.

Value

paths (the resolved file paths), invisibly.

See Also

render_plot(), pdf_pages(), repeat_()

Examples

plots <- list(
  wt = vplot(mtcars) |> mark_point(x = wt, y = mpg),
  hp = vplot(mtcars) |> mark_point(x = hp, y = mpg)
)
render_all(plots, tempdir())

Render a plot to a file

Description

Compiles a PlotSpec into a vellum::vl_scene() and writes it. The output format is taken from the file extension (.png, .svg, .pdf). vellum::render() also works on a plot directly, dispatching through the as_vellum_scene() seam.

Usage

render_plot(plot, path, text = "native", dpi = NULL, cvd = "none")

Arguments

plot

A PlotSpec.

path

Output file path.

text

For SVG output, how text is written (see vellum::render()).

dpi

Output resolution in dots per inch. NULL (default) uses the plot's authored resolution (set on vplot()); a number overrides it for this render, so the PNG's pixel dimensions become width * dpi by height * dpi. Ignored for .svg/.pdf, which are resolution-independent.

cvd

Colour-vision-deficiency simulation for a .png render: one of "none" (default), "protanopia", "deuteranopia", "tritanopia", or "achromatopsia". Use it to preview how a palette reads for a colour-blind viewer (pair with plot_lint(), which flags low contrast, and scale_pattern() / pattern_hatch(), which add a redundant non-colour encoding). Simulation is raster-only; it is ignored for .svg/.pdf.

Value

path, invisibly.

Examples

p <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
f <- tempfile(fileext = ".png")
render_plot(p, f)
render_plot(p, f, dpi = 300) # denser raster, same physical size
render_plot(p, f, cvd = "deuteranopia") # preview for red-green colour blindness

Repeat a view across fields

Description

Replicate a plot, re-pointing one or more encodings at a different data field each time, and arrange the copies as a composition (like concat(), so each sub-plot keeps its own scales and axes). Supply each aesthetic as a character vector of column names; all vectors must be the same length N, and are zipped to produce N sub-plots.

Usage

repeat_(plot, ..., ncol = NULL, nrow = NULL)

Arguments

plot

A PlotSpec; the repeated aesthetic(s) are set on every layer (added if not already mapped). In a multi-layer plot every layer therefore receives the re-pointed field, so any layer carrying its own data must contain the named field columns.

...

Named aesthetics, each a character vector of field names, e.g. x = c("wt", "hp", "disp").

ncol, nrow

Grid dimensions (passed to concat()).

Value

A PlotComposition.

Examples

repeat_(vplot(mtcars) |> mark_point(y = mpg), x = c("wt", "hp", "disp"))

Resolve scales as shared or independent across panels

Description

The scale-resolution lattice (after Vega-Lite): for each aesthetic, choose whether faceted panels share one trained scale or train independent ones. Every scale defaults to "shared"; facet_*(scales = "free_*") is sugar for setting x/y to "independent".

Usage

resolve_scale(plot, ...)

Arguments

plot

A PlotSpec.

...

Named arguments mapping an aesthetic (x, y, color, size, ...) to "shared" or "independent".

Details

A non-position aesthetic (color, fill, size, alpha, shape, linetype, linewidth, pattern, ...) set to "independent" is trained in each panel from that panel's data alone, so each panel spends the whole palette or range on its own values, and each panel gets its own legend, drawn beside its panel (the guide position "panel"): right of each panel by default, or on the side theme(legend.position = ) names (left of, above or below each panel, or inside it). Each column of panels (or row, for legends above or below) gets a legend track as wide (tall) as its largest legend. To collect them in the legend area instead, give the guide a position, e.g. guides(color = guide_legend(position = "right")); they are then titled with the scale title and the panel's strip text ("hp (cyl: 4)"). Scales left shared keep their single legend. colour is an alias for color; fill is its own scale. A plot with a single panel ignores the setting.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> facet_wrap(~cyl) |>
  resolve_scale(y = "independent")

# one colour legend beside each panel
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(gear)) |>
  facet_wrap(~cyl) |>
  resolve_scale(color = "independent")

# the per-panel legends collected on the right instead
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(gear)) |>
  facet_wrap(~cyl) |>
  resolve_scale(color = "independent") |>
  guides(color = guide_legend(position = "right"))

Alpha (opacity) scale

Description

Declare the scale for a mapped alpha aesthetic: data values map to an opacity range in ⁠[0, 1]⁠. An alpha legend is drawn automatically.

scale_alpha_manual() sets the opacity of each level of a discrete variable directly via values (named values match levels by name). scale_alpha_discrete() / scale_alpha_ordinal() spread the levels evenly over range; the discrete form warns that alpha is not advised for an unordered variable, the ordinal form does not.

Usage

scale_alpha(
  plot,
  range = NULL,
  limits = NULL,
  breaks = NULL,
  name = NULL,
  oob = NULL
)

scale_alpha_continuous(
  plot,
  range = NULL,
  limits = NULL,
  breaks = NULL,
  name = NULL,
  oob = NULL
)

scale_alpha_manual(
  plot,
  values,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_alpha_discrete(
  plot,
  range = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_alpha_ordinal(
  plot,
  range = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

Arguments

plot

A PlotSpec.

range

Numeric length-2 output opacity range, or NULL for the default c(0.1, 1).

limits

Numeric length-2 data domain, or NULL to train from the data.

breaks

Explicit legend breaks, or NULL.

name

Legend title, or NULL to derive from the encoding.

oob

What to do with values outside limits: "censor" (they get no opacity, so the mark is not drawn), "squish" (the opacity of the nearest limit), "keep" (extrapolated past the range), or a ⁠function(x, range)⁠. NULL (default) keeps them.

values

For scale_alpha_manual(), opacities in ⁠[0, 1]⁠, one per level (or named by level).

labels

For the discrete forms, legend labels (one per key, a vector named by level, or a function), or NULL.

na.value

For the discrete forms, the opacity drawn for missing values, or NULL to drop them.

drop

For the discrete forms, drop factor levels that no row uses (default TRUE, as in ggplot2): they get no legend key and no opacity, so the range is spread over the levels that remain. FALSE keeps every level. limits overrides it.

Details

A factor, character or logical mapped to alpha gets a discrete scale, its levels spread evenly over range, with a warning for an unordered variable (as in ggplot2).

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg, alpha = hp) |> scale_alpha(range = c(0.2, 1))
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, alpha = factor(cyl)) |>
  scale_alpha_manual(values = c(0.2, 0.5, 1))

Colour scales

Description

Declare the scale for the color or the fill channel. Continuous data get a perceptual ramp; discrete data get a qualitative palette. ⁠scale_*_manual()⁠ sets exact colours, ⁠scale_*_gradient()⁠ a two-point ramp, and ⁠scale_*_gradient2()⁠ a diverging three-point ramp (low–mid–high) centred on midpoint — for signed or anomaly data where a meaningful zero should sit at the neutral colour. The fill variants set the fill scale the same way: color and fill are separate scales with separate legends, as in ggplot2, drawn as one legend when they show the same title and keys. A legend is drawn automatically when colour or fill is mapped.

Usage

scale_color_continuous(
  plot,
  palette = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  oob = NULL
)

scale_color_discrete(
  plot,
  palette = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  drop = TRUE
)

scale_color_manual(
  plot,
  values,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_color_gradient(
  plot,
  low = "#132B43",
  high = "#56B1F7",
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_color_gradient2(
  plot,
  low = "#832424",
  mid = "#FFFFFF",
  high = "#3A3A98",
  midpoint = 0,
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_fill_continuous(
  plot,
  palette = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  oob = NULL
)

scale_color_gradientn(
  plot,
  colours,
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_fill_gradientn(
  plot,
  colours,
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_colour_gradientn(
  plot,
  colours,
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_fill_discrete(
  plot,
  palette = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  drop = TRUE
)

scale_fill_manual(
  plot,
  values,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_fill_gradient(
  plot,
  low = "#132B43",
  high = "#56B1F7",
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_fill_gradient2(
  plot,
  low = "#832424",
  mid = "#FFFFFF",
  high = "#3A3A98",
  midpoint = 0,
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_colour_continuous(
  plot,
  palette = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  oob = NULL
)

scale_colour_discrete(
  plot,
  palette = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  drop = TRUE
)

scale_colour_manual(
  plot,
  values,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_colour_gradient(
  plot,
  low = "#132B43",
  high = "#56B1F7",
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

scale_colour_gradient2(
  plot,
  low = "#832424",
  mid = "#FFFFFF",
  high = "#3A3A98",
  midpoint = 0,
  name = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  na.value = NULL,
  oob = NULL
)

Arguments

plot

A PlotSpec.

palette

A vector of colours, or a single palette name passed to grDevices::hcl.colors() (e.g. "Batlow", "Blues", "Set 2"; matched case/space-insensitively). NULL uses a sensible default.

limits

For the continuous colour scales (including the gradient ones), a length-2 numeric c(min, max) fixing the mapped data range (the direct form of lims(color = ...)). For ⁠scale_*_manual()⁠, the levels the scale covers.

breaks, labels

Explicit legend breaks / labels, or NULL.

name

Legend title, or NULL to derive from the encoding.

oob

For the continuous scales (⁠scale_*_continuous()⁠, ⁠_gradient()⁠, ⁠_gradient2()⁠, ⁠_gradientn()⁠), what to do with values outside limits: "censor" gives them the NA colour, "squish" the colour of the nearest limit, "keep" the same (a ramp cannot extend past its ends), or a ⁠function(x, range)⁠. NULL (default) squishes.

drop

For the discrete scales, drop factor levels that no row uses (default TRUE, as in ggplot2): they get no legend key and no palette entry, so the colours go to the levels that remain. FALSE keeps every level. limits overrides it.

values

For ⁠scale_*_manual()⁠, a vector of colours; if named, matched to data levels by name (unmatched levels draw grey).

na.value

For the gradient scales, the colour of missing (and censored) values; for ⁠scale_*_manual()⁠, also of levels outside limits. NULL keeps the default grey.

low, high

For ⁠scale_*_gradient()⁠/⁠scale_*_gradient2()⁠, the endpoint colours.

mid

For ⁠scale_*_gradient2()⁠, the midpoint colour.

midpoint

For ⁠scale_*_gradient2()⁠, the data value placed at mid (default 0); values above and below diverge to high and low.

colours

For ⁠scale_*_gradientn()⁠, an n-stop vector of colours the continuous ramp interpolates through.

Details

Continuous and binned ramps built from a plain colour vector are interpolated in the perceptually-uniform Oklab space, so they avoid the muddy, over-dark midtones and hue drift of sRGB blending. Designed perceptual palettes (the default, and hcl.colors() names) are already uniform and unaffected. Set options(vellumplot.color.interpolation = "srgb") (or "lab") to change the blend space globally.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = hp) |>
  scale_color_continuous(palette = "Batlow")

Identity scales

Description

Use the data values directly as the aesthetic — no training and no legend. The mapped column must already contain valid aesthetic values: colours for scale_color_identity() / scale_fill_identity(), sizes in mm for scale_size_identity(), and shape names for scale_shape_identity(). Useful when a column already holds the exact colours/sizes you want to draw.

Usage

scale_color_identity(plot)

scale_fill_identity(plot)

scale_colour_identity(plot)

scale_size_identity(plot)

scale_shape_identity(plot)

scale_alpha_identity(plot)

scale_linetype_identity(plot)

Arguments

plot

A PlotSpec.

Value

The modified PlotSpec.

Examples

df <- data.frame(x = 1:3, y = 1:3, col = c("red", "green", "blue"))
vplot(df) |> mark_point(x = x, y = y, color = col) |> scale_color_identity()

Edge colour / alpha / line-type scales

Description

Declare the scale for a mapped edge aesthetic on a vgraph() plot – the colour (mark_edges(color = )), opacity (⁠alpha = ⁠), or line type (⁠linetype = ⁠) of the edges. These are the edge counterparts of scale_color_continuous() / scale_alpha() / scale_linetype(): an edge aesthetic is trained and legended independently of the node scales, so a figure can map, say, node fill to a discrete community and edge colour to a continuous weight without the two collapsing into one legend. Each draws its own legend automatically.

Usage

scale_edge_color(
  plot,
  palette = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  midpoint = NULL
)

scale_edge_colour(
  plot,
  palette = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  midpoint = NULL
)

scale_edge_alpha(plot, range = NULL, limits = NULL, breaks = NULL, name = NULL)

scale_edge_linetype(plot, values = NULL, name = NULL)

Arguments

plot

A PlotSpec, normally from vgraph().

palette

For scale_edge_color(), a vector of colours or a single palette name (as in scale_color_continuous()); NULL for a default.

name

Legend title, or NULL to derive from the encoding.

midpoint

For scale_edge_color(), the data value placed at the ramp's midpoint (a diverging scale); NULL for an ordinary ramp.

range

For scale_edge_alpha(), the output opacity range c(min, max), or NULL for the default.

limits, breaks, labels

Data limits, explicit legend breaks, and explicit labels, or NULL to derive from the data.

values

For scale_edge_linetype(), a character vector of line types (as in scale_linetype()); NULL for the default palette.

Details

scale_edge_color() infers discrete vs continuous from the mapped data (a factor/character trains a discrete swatch legend; a number a colour bar), the same as the node colour scale. scale_edge_colour() is a British-spelling alias.

Value

The modified PlotSpec.

See Also

mark_edges(), scale_edge_width(), vgraph()

Examples

## Not run: 
g <- igraph::make_graph("Zachary")
g <- igraph::set_edge_attr(g, "w", value = runif(igraph::ecount(g)))
vgraph(g) |>
  mark_edges(color = w) |>
  mark_nodes(fill = factor(igraph::membership(igraph::cluster_louvain(g)))) |>
  scale_edge_color(palette = "Grays")

## End(Not run)

Edge-width scale

Description

Declare the scale for a mapped edge linewidth aesthetic (e.g. mark_edges(linewidth = weight) on a vgraph() plot). The data range is rescaled to a line-width range and an edge-width legend is drawn automatically.

Usage

scale_edge_width(plot, range = NULL, limits = NULL, breaks = NULL, name = NULL)

Arguments

plot

A PlotSpec.

range

Output line-width range c(min, max), or NULL for the default c(0.3, 3).

limits

Data limits c(min, max), or NULL to train from the data.

breaks

Explicit legend breaks, or NULL.

name

Legend title, or NULL to derive from the encoding.

Value

The modified PlotSpec.

See Also

mark_edges(), vgraph()

Examples

## Not run: 
g <- igraph::sample_gnp(20, 0.2)
g <- igraph::set_edge_attr(g, "w", value = runif(igraph::ecount(g)))
vgraph(g) |> mark_edges(linewidth = w) |> mark_nodes() |> scale_edge_width(range = c(0.3, 4))

## End(Not run)

Binned (classed) colour scales

Description

scale_fill_binned() / scale_color_binned() cut a continuous aesthetic into classes and colour each class with one step of a sequential palette — the standard choropleth scale. By default the classes follow ggplot2's binning (style = "extended"): about n "nice" class boundaries inside the data range, the outer classes widened to whole bins, and classes closed on the right, ⁠(a, b]⁠. A classification style chooses other breaks: quantile, equal, and pretty need no extra packages; other styles (e.g. "jenks", "fisher", "kmeans", "headtails") delegate to the optional classInt package (in Suggests) and error if it is absent. Those classes close on the left, ⁠[a, b)⁠.

The ggplot2-named binned colour scales follow ggplot2's binning: without breaks, about n.breaks "nice" class boundaries inside the data range, the outer classes widened to whole bins (with limits, the limits are the outer boundaries); classes close on the right, ⁠(a, b]⁠.

  • ⁠scale_*_steps()⁠ — a two-colour low–high ramp, each class taking the ramp's colour at its centre.

  • ⁠scale_*_steps2()⁠ — a diverging low–mid–high ramp centred on midpoint, each class taking the ramp's colour at its centre.

  • ⁠scale_*_stepsn()⁠ — an n-colour ramp colours, sampled at each class centre.

  • ⁠scale_*_fermenter()⁠ — a ColorBrewer palette's k-class colours (as scale_color_distiller(), but binned).

  • ⁠scale_*_viridis_b()⁠ — k evenly spaced viridis colours.

Usage

scale_fill_binned(
  plot,
  style = "extended",
  n = NULL,
  breaks = NULL,
  palette = NULL,
  labels = NULL,
  na_value = "grey80",
  name = NULL
)

scale_color_binned(
  plot,
  style = "extended",
  n = NULL,
  breaks = NULL,
  palette = NULL,
  labels = NULL,
  na_value = "grey80",
  name = NULL
)

scale_color_steps(
  plot,
  low = "#132B43",
  high = "#56B1F7",
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_colour_steps(
  plot,
  low = "#132B43",
  high = "#56B1F7",
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_fill_steps(
  plot,
  low = "#132B43",
  high = "#56B1F7",
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_color_steps2(
  plot,
  low = "#832424",
  mid = "#FFFFFF",
  high = "#3A3A98",
  midpoint = 0,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_color_stepsn(
  plot,
  colours,
  values = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_color_fermenter(
  plot,
  palette = 1,
  type = "seq",
  direction = -1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_color_viridis_b(
  plot,
  option = "viridis",
  direction = 1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_fill_steps2(
  plot,
  low = "#832424",
  mid = "#FFFFFF",
  high = "#3A3A98",
  midpoint = 0,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_fill_stepsn(
  plot,
  colours,
  values = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_fill_fermenter(
  plot,
  palette = 1,
  type = "seq",
  direction = -1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_fill_viridis_b(
  plot,
  option = "viridis",
  direction = 1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_colour_steps2(
  plot,
  low = "#832424",
  mid = "#FFFFFF",
  high = "#3A3A98",
  midpoint = 0,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_colour_stepsn(
  plot,
  colours,
  values = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_colour_fermenter(
  plot,
  palette = 1,
  type = "seq",
  direction = -1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

scale_colour_viridis_b(
  plot,
  option = "viridis",
  direction = 1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  n.breaks = NULL,
  na.value = "grey50",
  oob = NULL
)

Arguments

plot

A PlotSpec.

style

Classification style: "extended" (the default, ggplot2's breaks), "quantile", "equal", "pretty" (base R), or any classInt::classIntervals() style.

n

For "extended", the approximate number of class boundaries (default 5); for the other styles, the number of classes (default 5). Ignored when breaks is supplied.

breaks

Explicit class boundaries, overriding style/n. Under "extended" the data range is added as the outer boundaries (as ggplot2 adds its limits); under the other styles they are every boundary (length = number of classes + 1).

palette

A sequential palette: NULL (batlow), an grDevices::hcl.pals() name, or a vector of colours interpolated across the classes.

labels

Optional class labels (one per class); defaults to interval ranges like "(0, 10]".

na_value

Fill colour for NA values (shown as a distinct legend swatch). Default "grey80".

name

Legend title, or NULL to derive from the encoding.

low, mid, high, midpoint

For ⁠scale_*_steps()⁠, the end colours low and high; for ⁠scale_*_steps2()⁠, the end and midpoint colours and the data value at mid.

limits

For the ggplot2-named scales, a length-2 numeric c(min, max): the outer class boundaries.

n.breaks

For the ggplot2-named scales, the approximate number of class boundaries when breaks is NULL (default 5).

na.value

For the ggplot2-named scales, the colour of missing values.

oob

For the ggplot2-named scales, what to do with values outside the outer boundaries: "squish" (the default, as in ggplot2) colours them as the outer class, "censor" with na.value; or a ⁠function(x, range)⁠.

colours

For ⁠scale_*_stepsn()⁠, the colours of the ramp.

values

For ⁠scale_*_stepsn()⁠, the positions (between 0 and 1, one per colour, increasing) of colours along the ramp, or NULL to space them evenly.

type, direction

For ⁠scale_*_fermenter()⁠, the ColorBrewer family a numeric palette indexes and its order (see scale_color_brewer()); for ⁠scale_*_viridis_b()⁠, direction = -1 reverses the map.

option

For ⁠scale_*_viridis_b()⁠, the viridis map (see scale_color_viridis_c()).

Details

A colour vector palette is a ramp, sampled at each class's centre as in ggplot2; a named palette (and the default) gives one evenly spaced colour per class.

Value

The modified PlotSpec.

See Also

mark_sf(), scale_fill_continuous()

Examples

vplot(faithful) |>
  mark_point(x = eruptions, y = waiting, color = waiting) |>
  scale_color_binned()
## Not run: 
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
vplot(nc) |>
  mark_sf(fill = SID74) |>
  scale_fill_binned(style = "quantile", n = 5) |>
  coord_sf()

## End(Not run)
vplot(faithful) |>
  mark_point(x = eruptions, y = waiting, color = waiting - 70) |>
  scale_color_steps2()

Bivariate colour scales

Description

scale_fill_bivariate() colours a bi_class() column with a bivariate palette and draws its legend as a dim x dim grid of swatches, the x variable along the bottom and the y variable up the side (see guide_bivariate()). It is the scale half of a bivariate choropleth; it works on any mark with a fill (mark_sf() polygons, tiles, bars, points), and scale_color_bivariate() does the same for color.

Usage

scale_fill_bivariate(
  plot,
  palette = "DkBlue",
  dim = NULL,
  xlab = NULL,
  ylab = NULL,
  name = NULL,
  na_value = "grey80"
)

scale_color_bivariate(
  plot,
  palette = "DkBlue",
  dim = NULL,
  xlab = NULL,
  ylab = NULL,
  name = NULL,
  na_value = "grey80"
)

scale_colour_bivariate(
  plot,
  palette = "DkBlue",
  dim = NULL,
  xlab = NULL,
  ylab = NULL,
  name = NULL,
  na_value = "grey80"
)

Arguments

plot

A PlotSpec.

palette

A palette name for bi_pal() ("DkBlue", "GrPink", "DkViolet", "Brown"), or your own dim^2 colours, named by class ("1-1", "2-1", ...) or given in that order.

dim

Classes per variable (2, 3 or 4). NULL (default) takes it from the bi_class() column, falling back to 3.

xlab, ylab

The legend's axis titles. NULL uses the variable names recorded by bi_class().

name

A title above the legend grid. NULL (default) draws none — the axis titles already say what the colours mean. labs() also sets it.

na_value

Fill for features with a missing class. Default "grey80".

Details

A column made by bi_class() is recognised on its own, so the scale is only needed to change the palette or the axis titles. The class count is read from that column too. A plain character or factor column of "x-y" class labels also works with an explicit dim.

Hover and selection work as for any discrete colour scale: on an interactive plot each legend swatch is keyed to the features in its class.

Value

The modified PlotSpec.

See Also

bi_class(), guide_bivariate(), bi_pal()

Other bivariate: bi_class(), bi_pal(), guide_bivariate()

Examples

d <- bi_class(mtcars, hp, wt)
vplot(d) |>
  mark_point(x = hp, y = wt, color = bi_class, size = 2) |>
  scale_color_bivariate(palette = "GrPink", xlab = "Power", ylab = "Weight")

if (requireNamespace("sf", quietly = TRUE)) {
  nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
  nc <- bi_class(nc, BIR74, SID74)
  vplot(nc) |>
    mark_sf(fill = bi_class, color = "white", linewidth = 0.2) |>
    scale_fill_bivariate(xlab = "Births", ylab = "SIDS cases")
}

Hue, grey and ordinal colour scales

Description

ggplot2's other discrete colour scales, for code migrating from it.

Usage

scale_color_hue(
  plot,
  h = c(0, 360) + 15,
  c = 100,
  l = 65,
  h.start = 0,
  direction = 1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "grey50",
  drop = TRUE
)

scale_colour_hue(
  plot,
  h = c(0, 360) + 15,
  c = 100,
  l = 65,
  h.start = 0,
  direction = 1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "grey50",
  drop = TRUE
)

scale_fill_hue(
  plot,
  h = c(0, 360) + 15,
  c = 100,
  l = 65,
  h.start = 0,
  direction = 1,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "grey50",
  drop = TRUE
)

scale_color_grey(
  plot,
  start = 0.2,
  end = 0.8,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "red",
  drop = TRUE
)

scale_colour_grey(
  plot,
  start = 0.2,
  end = 0.8,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "red",
  drop = TRUE
)

scale_fill_grey(
  plot,
  start = 0.2,
  end = 0.8,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "red",
  drop = TRUE
)

scale_color_ordinal(
  plot,
  option = "viridis",
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "grey50",
  drop = TRUE
)

scale_colour_ordinal(
  plot,
  option = "viridis",
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "grey50",
  drop = TRUE
)

scale_fill_ordinal(
  plot,
  option = "viridis",
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = "grey50",
  drop = TRUE
)

Arguments

plot

A PlotSpec.

h

Range of hues, in degrees on the colour wheel.

c, l

Chroma and luminance of the hues.

h.start

Hue to start at.

direction

1 runs clockwise round the wheel, -1 anticlockwise.

name

Legend title, or NULL to derive from the encoding.

breaks, labels

The levels the legend shows and their labels (one per shown level, a vector named by level, or a function), or NULL.

limits

The levels the scale covers, or NULL for those in the data.

na.value

Colour for missing values (and levels outside limits).

drop

For the discrete scales, drop factor levels that no row uses (default TRUE, as in ggplot2): they get no legend key and no palette entry, so the colours go to the levels that remain. FALSE keeps every level. limits overrides it.

start, end

Grey levels of the first and last colour, in ⁠[0, 1]⁠.

option

For ⁠scale_*_ordinal()⁠, the viridis map (see scale_color_viridis_d()).

Details

  • ⁠scale_*_hue()⁠ — evenly spaced hues around the HCL colour wheel (ggplot2's default discrete palette, via scales::pal_hue()).

  • ⁠scale_*_grey()⁠ — a grey ramp from start to end (0 is black, 1 white), via scales::pal_grey().

  • ⁠scale_*_ordinal()⁠ — the viridis palette ggplot2 uses for an ordered factor (as scale_color_viridis_d()).

The colours depend on the number of levels, so they are drawn when the plot is compiled.

Value

The modified PlotSpec.

See Also

scale_color_discrete(), scale_viridis

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl)) |>
  scale_color_hue(l = 45)
vplot(mtcars) |>
  mark_bar(x = factor(gear), fill = factor(cyl)) |>
  scale_fill_grey()

Line-type scale

Description

Declare the scale for a mapped (discrete) linetype aesthetic. Levels cycle through a default set of line types unless values is given. A line-type legend is drawn automatically. Applies to line-like marks (mark_line(), mark_step()).

Usage

scale_linetype(
  plot,
  values = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_linetype_manual(
  plot,
  values,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_linetype_discrete(
  plot,
  values = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

Arguments

plot

A PlotSpec.

values

Character vector of line types (each one of "solid", "dashed", "dotted", "dotdash", "longdash", "twodash"), or NULL for the default set. For scale_linetype_manual() values is required, and may also be ggplot2's numeric line types (1 solid, 2 dashed, ... 6 twodash). Named values are matched to levels by name.

name

Legend title, or NULL to derive from the encoding.

breaks, labels, limits

As for scale_shape().

na.value

The line type drawn for missing values, or NULL.

drop

For the discrete scales, drop factor levels that no row uses (default TRUE, as in ggplot2): they get no legend key and no palette entry, so the colours go to the levels that remain. FALSE keeps every level. limits overrides it.

Value

The modified PlotSpec.

Examples

df <- data.frame(x = rep(1:10, 2), y = rnorm(20), g = rep(c("a", "b"), each = 10))
vplot(df) |> mark_line(x = x, y = y, linetype = g)
vplot(df) |>
  mark_line(x = x, y = y, linetype = g) |>
  scale_linetype_manual(values = c(a = "dotted", b = "solid"))

Line-width scale

Description

Declare the scale for a mapped linewidth aesthetic on a stroked mark – mark_line(), mark_step(), or mark_segment(). Data values are rescaled linearly onto a line-width range (in lwd units, as everywhere else in the package) and a line-width legend is drawn automatically.

Usage

scale_linewidth(plot, range = NULL, limits = NULL, breaks = NULL, name = NULL)

scale_linewidth_continuous(
  plot,
  range = NULL,
  limits = NULL,
  breaks = NULL,
  name = NULL
)

Arguments

plot

A PlotSpec.

range

Output line-width range c(min, max), or NULL for the default c(0.5, 4).

limits

Data limits c(min, max), or NULL to train from the data.

breaks

Explicit legend breaks, or NULL.

name

Legend title, or NULL to derive from the encoding.

Details

On mark_line() and mark_step(), a mapped linewidth draws each series as one continuous stroke whose width tapers smoothly between the values at its vertices (via vellum's lines_grob(lwd_profile = )). The stroke is built as a filled outline at render time, so it looks the same in PNG, SVG and PDF and stays one element per series in vellum::scene_model() and the SVG. A constant ⁠linewidth =⁠ is unaffected and still draws an ordinary stroke.

A tapered stroke has one colour and no dash pattern, so a series falls back to one segment per span – each at the mean of its two endpoint widths, so the width steps at every vertex – when it also maps a continuous colour that varies along the series (each segment then takes its own colour), uses a dashed or dotted linetype, is drawn with a sketch theme, or has a missing width. That fallback emits one path element per segment, worth knowing before combining those with tens of thousands of rows. mark_segment() is already one element per row and takes one width per segment.

For edges on a vgraph() plot, use scale_edge_width() instead: an edge's width is trained and legended independently of the line-width scale. That also means guides(linewidth = ) and lims(linewidth = ) address this scale; use guides(edge_width = ) / lims(edge_width = ) for a graph's edges.

A missing (NA) width takes its segment's width from whichever endpoint is known, so one missing value thins the line rather than erasing the two segments that meet at it. A segment missing a width at both ends is dropped. (A series with a missing width is drawn per segment, as above.)

Value

The modified PlotSpec.

See Also

mark_line(), mark_step(), mark_segment(), scale_edge_width()

Examples

vplot(pressure) |>
  mark_line(x = temperature, y = pressure, linewidth = pressure) |>
  scale_linewidth(range = c(0.5, 5))

Pattern (texture) scale

Description

Map a discrete variable to fill textures – the greyscale- and colour-vision-safe companion of a fill palette – via a filled mark's pattern aesthetic: mark_bar(x = g, y = n, pattern = series). Each level takes a distinct pattern_stripe()-family texture. Applies to the filled marks (bar, area, tile, rect, boxplot, violin, hull).

Usage

scale_pattern(plot, values = NULL, name = NULL)

Arguments

plot

A PlotSpec.

values

Optional textures, one per level: a character vector of builder names ("stripe", "crosshatch", "grid", "dot", "checker"), or a list of vellum_pattern objects (e.g. from pattern_stripe()). NULL (default) cycles a built-in palette of distinct textures.

name

Optional legend title.

Value

The modified PlotSpec.

See Also

pattern_stripe(), scale_shape()

Examples

df <- data.frame(g = c("a", "b", "c"), n = c(3, 5, 2))
vplot(df) |> mark_bar(x = g, y = n, pattern = g) |> scale_pattern()

Shape scale

Description

Declare the scale for a mapped (discrete) shape aesthetic. Levels cycle through a default set of marker shapes unless values is given. A shape legend is drawn automatically.

Usage

scale_shape(
  plot,
  values = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_shape_manual(
  plot,
  values,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_shape_discrete(
  plot,
  values = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

Arguments

plot

A PlotSpec.

values

Character vector of shapes, or NULL for the default. Each is either a built-in marker ("circle", "square", "triangle", "diamond", "plus", "cross", "triangle_down", "star") or an SVG icon — a path d string (what icon sets ship) or a path to a .svg file. SVG values are drawn as crisp vector markers (via vellum::svg_grob()) and the legend shows the icon; the size aesthetic scales them.

For scale_shape_manual() values is required, and may also be ggplot2's numeric shape codes (16, 17, ...), which map to the nearest marker. As in ggplot2, the open codes (0-14) draw an outline in the point colour, the solid ones (15-20) fill with it, and the bordered ones (21-25) fill with fill inside a color outline (unfilled when no fill is given). Of the solid codes, 15-18 have no outline and 20 is 2/3 the size of 19, as in ggplot2. Each code draws at R's size for it: the triangles are larger than the circle (equal in area), the bordered square (22) a little smaller than the open and solid ones, and so on. By name, these are "circle open", "circle filled", "circle bare" (no outline), "circle small" and so on for every built-in marker; the plain names ("triangle") keep vellum's own sizes. Named values are matched to levels by name.

name

Legend title, or NULL to derive from the encoding.

breaks

The levels the legend shows (and their order), or NULL for all of them.

labels

Legend labels: one per shown level, a vector named by level, or a function of the levels; NULL keeps the levels.

limits

The levels the scale covers (a character vector), or NULL for the levels in the data. Data outside limits draws as na.value.

na.value

The shape drawn for missing values (default a circle).

drop

For the discrete scales, drop factor levels that no row uses (default TRUE, as in ggplot2): they get no legend key and no palette entry, so the colours go to the levels that remain. FALSE keeps every level. limits overrides it.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg, shape = factor(cyl))
# SVG icon markers, one per level:
star <- "M12 2l3 7h7l-5.5 4.5 2 7-6.5-4.5-6.5 4.5 2-7L2 9h7z"
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, shape = factor(cyl)) |>
  scale_shape(values = c(star, star, star))
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, shape = factor(cyl)) |>
  scale_shape_manual(values = c("4" = 16, "6" = 17, "8" = 15))

Size scale

Description

Declare the scale for a mapped size aesthetic: data values map linearly to a point-size range (in mm). A size legend is drawn automatically.

scale_size_area() maps the data value to the marker's area rather than its radius, with value 0 at size 0 — the perceptually honest default for bubble charts (a value twice as large looks twice as big in ink). max_size is the size (mm) of the largest value.

scale_radius() is ggplot2's radius-proportional size scale. vellumplot's scale_size() already maps the value linearly to the marker size, so it is scale_size() with ggplot2's default range = c(1, 6).

scale_size_binned() cuts the variable into classes and gives each class one size, the size of its centre on an area scale (as ggplot2's scale_size_binned()); the legend keys the classes. Without breaks the class boundaries are n.breaks "nice" values inside the data range, and the outer classes are widened to whole bins, as in ggplot2.

scale_size_manual() sets the size (mm) of each level of a discrete variable directly via values (named values match levels by name). scale_size_discrete() / scale_size_ordinal() spread the levels evenly (by area) over range; the discrete form warns that size is not advised for an unordered variable, the ordinal form does not.

Usage

scale_size(
  plot,
  range = NULL,
  limits = NULL,
  breaks = NULL,
  name = NULL,
  oob = NULL
)

scale_size_area(plot, max_size = 6, limits = NULL, breaks = NULL, name = NULL)

scale_size_continuous(
  plot,
  range = NULL,
  limits = NULL,
  breaks = NULL,
  name = NULL,
  oob = NULL
)

scale_radius(
  plot,
  range = c(1, 6),
  limits = NULL,
  breaks = NULL,
  name = NULL,
  oob = NULL
)

scale_size_binned(
  plot,
  range = NULL,
  limits = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  n.breaks = NULL
)

scale_size_manual(
  plot,
  values,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_size_discrete(
  plot,
  range = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

scale_size_ordinal(
  plot,
  range = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  drop = TRUE
)

Arguments

plot

A PlotSpec.

range

Numeric length-2 output size range in mm, or NULL for the default c(1, 4).

limits

Numeric length-2 data domain, or NULL to train from the data.

breaks

Explicit legend breaks, or NULL.

name

Legend title, or NULL to derive from the encoding.

oob

What to do with values outside limits: "censor" (they get no size, so the mark is not drawn), "squish" (the size of the nearest limit), "keep" (extrapolated past the range), or a ⁠function(x, range)⁠. NULL (default) keeps them.

max_size

For scale_size_area(), the point size (mm) of the largest value.

labels

For scale_size_binned() and the discrete forms, legend labels (one per key, or a function), or NULL.

n.breaks

For scale_size_binned(), the approximate number of class boundaries (default 5) when breaks is NULL.

values

For scale_size_manual(), the sizes in mm, one per level (or named by level).

na.value

For the discrete forms, the size drawn for missing values, or NULL to drop them.

drop

For the discrete forms, drop factor levels that no row uses (default TRUE, as in ggplot2): they get no legend key and no size, so the range is spread over the levels that remain. FALSE keeps every level. limits overrides it.

Details

A factor, character or logical mapped to size gets a discrete scale: the levels spread evenly (by area) over range, the legend keys are the levels, and breaks picks which of them it shows. As in ggplot2, an unordered variable warns that size is not advised for it; an ordered factor does not.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg, size = hp) |> scale_size(range = c(1, 8))
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, size = hp) |>
  scale_size_area(max_size = 10)
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, size = factor(cyl)) |>
  scale_size_manual(values = c(2, 4, 8))

Viridis and ColorBrewer scales

Description

Named convenience constructors for popular palettes, easing migration from ggplot2. They are thin wrappers over the ⁠palette =⁠ argument of scale_color_continuous() / scale_color_discrete() (any grDevices::hcl.colors() name works there directly).

Usage

scale_color_viridis_c(
  plot,
  option = "viridis",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  oob = NULL
)

scale_color_viridis_d(
  plot,
  option = "viridis",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  drop = TRUE
)

scale_fill_viridis_c(
  plot,
  option = "viridis",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  oob = NULL
)

scale_fill_viridis_d(
  plot,
  option = "viridis",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  drop = TRUE
)

scale_color_brewer(
  plot,
  palette = "Blues",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  type = "seq",
  direction = 1,
  drop = TRUE
)

scale_fill_brewer(
  plot,
  palette = "Blues",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  type = "seq",
  direction = 1,
  drop = TRUE
)

scale_color_distiller(
  plot,
  palette = "Blues",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  type = "seq",
  direction = -1,
  limits = NULL,
  na.value = NULL,
  oob = NULL
)

scale_fill_distiller(
  plot,
  palette = "Blues",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  type = "seq",
  direction = -1,
  limits = NULL,
  na.value = NULL,
  oob = NULL
)

scale_colour_viridis_c(
  plot,
  option = "viridis",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  limits = NULL,
  na.value = NULL,
  oob = NULL
)

scale_colour_viridis_d(
  plot,
  option = "viridis",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  drop = TRUE
)

scale_colour_brewer(
  plot,
  palette = "Blues",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  type = "seq",
  direction = 1,
  drop = TRUE
)

scale_colour_distiller(
  plot,
  palette = "Blues",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  type = "seq",
  direction = -1,
  limits = NULL,
  na.value = NULL,
  oob = NULL
)

Arguments

plot

A PlotSpec.

option

Which viridis map (see above).

name, breaks, labels

As for scale_color_continuous().

limits, oob, na.value

For the continuous scales (⁠_viridis_c()⁠, ⁠_distiller()⁠), the mapped data range c(min, max), what to do with values outside it ("censor", "squish", "keep" or a function; NULL, the default, squishes) and the colour of missing values, as for scale_color_continuous().

drop

For the discrete scales, drop factor levels that no row uses (default TRUE, as in ggplot2): they get no legend key and no palette entry, so the colours go to the levels that remain. FALSE keeps every level. limits overrides it.

palette

A ColorBrewer palette name or index (see above), or a grDevices::hcl.colors() palette name.

type

When palette is a number, which ColorBrewer family it indexes: "seq" (sequential), "div" (diverging) or "qual" (qualitative).

direction

1 keeps a ColorBrewer palette's order, -1 reverses it. ⁠scale_*_distiller()⁠ defaults to -1, as in ggplot2, so high values are light. Ignored for non-ColorBrewer palette names.

Details

  • ⁠scale_*_viridis_c()⁠ / ⁠scale_*_viridis_d()⁠ — the perceptually-uniform, colour-vision-deficient-safe viridis maps, continuous (⁠_c⁠) or discrete (⁠_d⁠). option picks the map: "viridis", "plasma", "inferno", "cividis", "rocket", or "mako" (unknown options fall back to viridis).

  • ⁠scale_*_brewer()⁠ — a discrete ColorBrewer palette (sequential, diverging or qualitative, via scales::pal_brewer()); ⁠scale_*_distiller()⁠ — the same palette's 7-class ramp interpolated for continuous data. palette is a ColorBrewer name ("Set1", "Dark2", "Paired", "Blues", "RdBu", "Spectral", ...; matched ignoring case, spaces and punctuation, so "Set 2" is "Set2") or an index into the palettes of type. Any other grDevices::hcl.colors() name (e.g. "Batlow") is passed through unchanged, as by scale_color_discrete() / scale_color_continuous().

Value

The modified PlotSpec.

See Also

scale_color_continuous()

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg, color = hp) |> scale_color_viridis_c()
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl)) |>
  scale_color_brewer(palette = "Set1")
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = hp) |>
  scale_color_distiller(palette = "Spectral")

Binned position scales

Description

scale_x_binned() / scale_y_binned() cut a continuous position variable into bins: axis ticks fall at the bin boundaries and each datum is drawn at its bin centre. Breaks use the same classification as the binned colour scales (style/n; classInt for jenks/fisher/… — a Suggest). Handy to summarise a dense continuous axis, or to place mark_bar() on a binned continuous x.

Usage

scale_x_binned(
  plot,
  style = "pretty",
  n = 10,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

scale_y_binned(
  plot,
  style = "pretty",
  n = 10,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

Arguments

plot

A PlotSpec.

style

Binning style: "pretty" (default), "equal", "quantile", or a classInt style.

n

Target number of bins.

breaks

Explicit bin boundaries (overrides style/n), or NULL.

labels

Explicit boundary labels, or NULL to format the boundaries.

name

Axis title, or NULL to derive from the encoding.

guide

The axis guide: guide_axis() to stagger, rotate or thin the labels, "none" for no labels or ticks, or NULL (default) for the plain axis. Same as guides(x = ) / guides(y = ).

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> scale_x_binned(n = 6)

Position scales

Description

Declare a position scale to override the trained default. scale_x_continuous() / scale_y_continuous() handle numeric (and date/time) axes; scale_x_discrete() / scale_y_discrete() handle categorical (band) axes and let you set the level order via limits.

scale_x_log10(), scale_x_sqrt() and scale_x_reverse() (and their y forms) are shortcuts for scale_x_continuous(trans = "log10") and so on, as in ggplot2; ... takes the other arguments of scale_x_continuous().

Usage

scale_x_continuous(
  plot,
  limits = NULL,
  trans = "identity",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  expand = NULL,
  sec.axis = NULL,
  oob = NULL,
  guide = NULL
)

scale_y_continuous(
  plot,
  limits = NULL,
  trans = "identity",
  breaks = NULL,
  labels = NULL,
  name = NULL,
  expand = NULL,
  sec.axis = NULL,
  oob = NULL,
  guide = NULL
)

scale_x_log10(plot, ...)

scale_x_sqrt(plot, ...)

scale_x_reverse(plot, ...)

scale_y_log10(plot, ...)

scale_y_sqrt(plot, ...)

scale_y_reverse(plot, ...)

scale_x_discrete(
  plot,
  limits = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  drop = TRUE,
  guide = NULL
)

scale_y_discrete(
  plot,
  limits = NULL,
  name = NULL,
  breaks = NULL,
  labels = NULL,
  drop = TRUE,
  guide = NULL
)

Arguments

plot

A PlotSpec.

limits

For continuous scales a numeric length-2 domain c(min, max); for discrete scales a character vector of levels (sets order / subset). NULL trains from the data.

trans

Transformation: "identity" (default), "log10", "sqrt", "symlog" (symmetric log — linear through zero, logarithmic in the tails, so signed data and zero/negatives read on one axis), "reverse", or a scales::transform_log10()-style transform object.

breaks, labels

Explicit break positions (data units) and their labels, or NULL to compute them. On a discrete scale breaks is the levels that get a tick, and labels a character vector (one per break, or named by level) or a function of the levels.

name

Axis title, or NULL to derive from the encoding.

expand

Axis padding beyond the data. NULL (default) keeps the usual 5% breathing room; a numeric c(mult, add) sets a proportion of the range plus a constant (either may be 0), applied to both ends. Both act in the scale's transformed space, so on a trans = "log10" axis add is in log units (matching how the axis is drawn). Use expand = c(0, 0) to clamp the axis exactly to the data (e.g. a bar chart's baseline), or expand = c(0.1, 0) for a wider margin.

sec.axis

A secondary axis from sec_axis() / dup_axis(), drawn on the opposite edge, or NULL for none. Continuous Cartesian plots only (see sec_axis() for the current limitations).

oob

What to do with values outside limits, as in scales::oob_censor() and friends: "censor" drops them (they become NA and are not drawn), "squish" moves them onto the nearest limit, "keep" draws them where they fall, clipped by the panel. A function ⁠function(x, range)⁠ such as scales::oob_squish_any() also works. NULL (default) is "keep" on a position axis. Infinite values are never out of bounds: x = Inf sits on the panel edge.

guide

The axis guide: guide_axis() to stagger, rotate or thin the labels, "none" for no labels or ticks, or NULL (default) for the plain axis. Same as guides(x = ) / guides(y = ).

...

For the transform shortcuts, further arguments to scale_x_continuous() / scale_y_continuous() (not trans).

drop

For discrete scales, drop factor levels that do not occur in the data (default TRUE, as in ggplot2). limits overrides it.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> scale_x_continuous(limits = c(0, 6))
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> scale_y_continuous(trans = "sqrt")

Date and time position scales

Description

Position scales for Date (⁠scale_*_date⁠), date-time POSIXct (⁠scale_*_datetime⁠), and time-of-day / difftime / hms (⁠scale_*_time⁠) axes. A Date/POSIXct column already gets a sensible date axis automatically; declare one of these to control the break interval or the label format.

Usage

scale_x_date(
  plot,
  limits = NULL,
  date_breaks = NULL,
  date_labels = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

scale_y_date(
  plot,
  limits = NULL,
  date_breaks = NULL,
  date_labels = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

scale_x_datetime(
  plot,
  limits = NULL,
  date_breaks = NULL,
  date_labels = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

scale_y_datetime(
  plot,
  limits = NULL,
  date_breaks = NULL,
  date_labels = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

scale_x_time(
  plot,
  limits = NULL,
  date_breaks = NULL,
  date_labels = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

scale_y_time(
  plot,
  limits = NULL,
  date_breaks = NULL,
  date_labels = NULL,
  breaks = NULL,
  labels = NULL,
  name = NULL,
  guide = NULL
)

Arguments

plot

A PlotSpec.

limits

Length-2 vector giving the axis range (same class as the data), or NULL to train from the data.

date_breaks

A break interval string, e.g. "1 month", "2 weeks", "10 years" (passed to scales::breaks_width()). NULL uses pretty().

date_labels

A base::strftime() format string for the tick labels, e.g. "%b %Y". NULL uses the default format.

breaks, labels

Explicit break positions / labels (override date_breaks/date_labels), or NULL.

name

Axis title, or NULL to derive from the encoding.

guide

The axis guide: guide_axis() to stagger, rotate or thin the labels, "none" for no labels or ticks, or NULL (default) for the plain axis. Same as guides(x = ) / guides(y = ).

Value

The modified PlotSpec.

Examples

df <- data.frame(day = as.Date("2020-01-01") + 0:364, y = cumsum(rnorm(365)))
vplot(df) |>
  mark_line(x = day, y = y) |>
  scale_x_date(date_breaks = "3 months", date_labels = "%b %Y")

Secondary axes

Description

Add a secondary axis to a continuous position scale: a second set of ticks and labels on the opposite edge (top for x, right for y), computed as a 1:1 monotonic transform of the primary axis. Pass the result to the sec.axis argument of scale_x_continuous() / scale_y_continuous(). This is a labelling convenience (unit conversions, count/proportion dual readouts, duplicating an axis on a wide plot) — not an independent second axis with its own data.

Usage

sec_axis(transform = ~., name = NULL, breaks = NULL, labels = NULL)

dup_axis(transform = ~., name = NULL, breaks = NULL, labels = NULL)

Arguments

transform

The primary-to-secondary mapping: a formula using . (e.g. ~ . * 1.8 + 32), a function, or a scales::transform_log10()-style transform object. Must be monotonic over the axis range. Defaults to the identity, ~ ..

name

Secondary axis title, or NULL for none.

breaks

Break positions in secondary units, or NULL to compute them.

labels

A character vector of labels (one per break) or a labelling function, or NULL for the default number format.

Details

sec_axis() maps the primary axis through transform; dup_axis() is the identity special case (a plain duplicate) with tidy defaults.

Value

A SecAxisSpec to pass to sec.axis.

Limitations (current version)

Secondary axes are supported only on continuous position scales under the default Cartesian coordinate system, with shared scales across facets. Combining sec.axis with coord_flip() / coord_polar() / coord_trans(), with free facet scales, or with add_marginal() raises an error. In a plot composition (| / /) the secondary axis is not drawn.

See Also

scale_x_continuous()

Examples

# Celsius with a Fahrenheit axis on top
vplot(data.frame(t = 0:100, y = (0:100)^2)) |>
  mark_line(x = t, y = y) |>
  scale_x_continuous(name = "°C", sec.axis = sec_axis(~ . * 1.8 + 32, name = "°F"))

# Duplicate the y axis on the right
vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  scale_y_continuous(sec.axis = dup_axis())

Declare an interval (brush) selection

Description

An interval selection is filled by dragging a brush over the plot. The brushed pixel range is converted to a data-value range on each of the encodings (through the panel's scale), and every element whose data values fall inside that range is a member. condition() and filter_by() react to it exactly as they do to a select_point() selection: highlight/dim members, or show only them. Clearing the brush (a click on empty space, or Escape) empties the selection.

Usage

select_interval(
  plot,
  name,
  encodings = c("x", "y"),
  region = c("rect", "lasso"),
  empty = TRUE,
  on = NULL,
  bind = NULL
)

Arguments

plot

A PlotSpec (piped form), or a selection name string (free-standing form).

name

The selection name (piped form), referenced by condition() and filter_by().

encodings

The position channels the brush constrains: c("x", "y") (default, a rectangle), "x" or "y".

region

"rect" (default, a brush rectangle) or "lasso" (a freehand polygon; membership by element position inside the polygon).

empty

Whether an empty selection contains all elements (TRUE, default, so an untouched plot shows its full self and brushing narrows it) or none (FALSE).

on

Deprecated alias for encodings: "x", "y" or "xy".

bind

NULL (default) for a brush, or "scales" to bind the selection to the view's own pan/zoom domain (Vega-Lite's bind: "scales"; see the section below). A "scales" selection must use region = "rect".

Details

Membership is by data value, so it follows the scale rather than the drawn shapes:

  • continuous (including log10, sqrt and reverse axes): the element's value lies in the brushed data range;

  • date / datetime: the same test on the date's numeric value;

  • discrete: the element's category is one whose band centre the brush covers.

With encodings = c("x", "y") (the default) the brush is a rectangle and both values are tested; with "x" it spans the panel's full height and only the x value is tested; "y" is the transpose. In a faceted plot the data range applies to every panel, so brushing one facet selects matching rows in all of them.

The selection lives in the plot spec, so it is inert on a static render and is enacted by a capable host (vellumwidget::as_widget()) without Shiny. Under Shiny the members are reported in ⁠input$<id>_selected⁠ and the brushed data range in ⁠input$<id>_brush⁠.

Like select_point(), it is pipe-first (attach to the plot and return it) or free-standing (call with the name as the first argument, then share it across views with add_selection() / filter_by()).

Value

A PlotSpec (piped form) or a SelectionSpec (free-standing form).

Driving another view's zoom (overview + detail)

An interval selection can set the visible range of another view: give the detail view a bind_scale() that names the selection, and brushing the overview zooms the detail to the brushed range (clearing the brush resets it). This is Vega-Lite's scale = list(domain = list(param = "brush")).

bind = "scales" is Vega-Lite's other half: the selection is bound to the scales of the view it is registered on. No brush is drawn; panning and zooming that view (wheel, pinch, drag in pan mode, the navigator) is the selection, its interval the visible data range on encodings, and resetting the zoom empties it. Pair it with bind_scale() on another view for linked zoom, or with condition() / filter_by() to react to the visible window.

See Also

select_point(), condition(), filter_by(), add_selection(), bind_scale()

Examples

df <- data.frame(x = 1:20, y = sqrt(1:20), g = rep(c("a", "b"), 10))

# brush an x range: points outside it fade to grey
vplot(df) |>
  mark_point(x = x, y = y, color = condition("brush", g, "grey80")) |>
  select_interval("brush", encodings = "x")

# brush a rectangle and show only the rows inside it
vplot(df) |>
  mark_point(x = x, y = y) |>
  select_interval("box", encodings = c("x", "y")) |>
  filter_by("box")

# free-standing: brush one view, filter another
sel <- select_interval("brush", encodings = "x")
hconcat(
  vplot(df) |> mark_point(x = x, y = y) |> add_selection(sel),
  vplot(df) |> mark_bar(x = g, y = y) |> filter_by(sel)
)

# overview + detail: brushing the overview zooms the detail
brush <- select_interval("brush", encodings = "x")
vconcat(
  vplot(df) |> mark_line(x = x, y = y) |> add_selection(brush),
  vplot(df) |> mark_line(x = x, y = y) |> bind_scale(brush)
)

# linked zoom: zooming the left view zooms the right one along x
zoom <- select_interval("zoom", encodings = "x", bind = "scales")
hconcat(
  vplot(df) |> mark_point(x = x, y = y) |> add_selection(zoom),
  vplot(df) |> mark_point(x = x, y = y) |> bind_scale(zoom)
)

Highlight a node's graph neighbourhood

Description

A network-aware select_point() preset for vgraph() plots: pointing at (or clicking) a node selects its neighbourhood — the node, its incident edges, and its adjacent nodes — so a host spotlights them and dims the rest. Pointing at an edge highlights the edge and its two endpoint nodes. It builds on the node/edge identity vgraph() emits for an interactive plot (each node keyed by its vertex name, each edge carrying its endpoint names); the host reconstructs the adjacency and projects the gesture across it.

Usage

select_neighbours(
  plot,
  name = "neighbours",
  on = c("hover", "click"),
  degree = 1L,
  edges = TRUE,
  empty = TRUE
)

Arguments

plot

A PlotSpec, normally from vgraph() (piped form), or a selection name string (free-standing form).

name

The selection name. Defaults to "neighbours".

on

The gesture: "hover" (default) or "click".

degree

How many hops out from the pointed node to include (1, the default, is the immediate neighbourhood; 2 adds neighbours-of-neighbours).

edges

Whether to include the incident edges in the highlight (TRUE, default) or only the nodes.

empty

Whether an empty selection matches all elements (TRUE, default — an un-hovered graph shows its full self) or none.

Details

Like the other selections it is inert on a static render and enacted by a capable host (vellumwidget). On its own it spotlights the neighbourhood; pair it with condition() to restyle members explicitly, or filter_by() to show only the neighbourhood.

Value

A PlotSpec (piped form) or a SelectionSpec (free-standing form).

See Also

select_point(), condition(), vgraph(), mark_edges()

Examples

## Not run: 
g <- igraph::make_graph("Zachary")
vgraph(g) |>
  mark_edges() |>
  mark_nodes(size = 3) |>
  select_neighbours(on = "hover")

## End(Not run)

Declare an interactive selection

Description

A selection is a named set of data elements defined by a user gesture. On its own it does nothing visible; refer to it from condition() (style by membership), filter_by() (show only members), or bind_scale() (drive another panel's view). Selections are part of the plot spec, so they travel with it, serialise with it, and are enacted by any capable host (vellumwidget). They are inert on a static render.

Usage

select_point(
  plot,
  name,
  on = c("click", "hover"),
  fields = NULL,
  group_by = NULL,
  toggle = TRUE,
  empty = TRUE
)

Arguments

plot

A PlotSpec (piped form), or a selection name string (free-standing form).

name

The selection name (piped form) — a string other nodes reference.

on

The gesture: "click" (default) or "hover".

fields

For a point selection, the column name(s) whose match extends membership: clicking one element selects every row equal to it on these fields (e.g. fields = "grp" selects the whole group). NULL (default) selects only the clicked element. group_by is an alias.

group_by

Alias for fields.

toggle

For a point selection, whether clicking toggles membership (TRUE, default) or replaces it (FALSE, single-select).

empty

Whether an empty selection contains all elements (TRUE, default — so an unselected plot shows its full self and selecting narrows) or none (FALSE).

Details

select_point() is driven by a click or hover (or a legend value). For a selection driven by a drag (a brush over a data range), see select_interval().

It is pipe-first (attach to the plot and return it) or free-standing (call with the name as the first argument to get a SelectionSpec you can share across views, then attach with add_selection()).

Value

A PlotSpec (piped form) or a SelectionSpec (free-standing form).

See Also

select_interval(), condition(), filter_by(), add_selection(), bind_scale()

Examples

df <- data.frame(x = 1:10, y = runif(10), g = rep(c("a", "b"), 5))

# highlight on hover (piped)
vplot(df) |>
  mark_point(x = x, y = y, color = condition("hi", g, "grey80")) |>
  select_point("hi", on = "hover")

# free-standing, for cross-view use
sel <- select_point("pick")

Shadow layer effect

Description

Draws dark, low-opacity copies of a stroked or point mark beneath the original, offset by (x, y) and softened by stacking a few widened copies — a drop shadow (with an offset) or an ambient shadow (offset 0). Applies to the same marks as glow().

Usage

shadow(
  x = 0.5,
  y = -0.5,
  color = "black",
  alpha = 0.3,
  spread = 1.5,
  layers = 3L
)

Arguments

x, y

Shadow offset in millimetres (+x right, +y up). Defaults to a small down-right drop.

color

Shadow colour.

alpha

Opacity of each copy.

spread

Softening spread, in millimetres, over which the copies widen.

layers

Number of stacked copies (more = softer).

Details

The offset is an absolute distance in millimetres (+x right, +y up), resolved device-side, so a drop shadow stays the same physical distance and is isotropic regardless of the panel's size or aspect (via vellum's compound npc + mm unit).

Value

A ShadowSpec object for a mark's effects list.

See Also

glow(), outline()

Examples

df <- data.frame(x = 1:20, y = cumsum(rnorm(20)))
vplot(df) |> mark_line(x = x, y = y, effects = list(shadow()))

Hand-drawn ("sketch") rendering

Description

sketch() is vellum::sketch(), re-exported — the one vocabulary vellumplot speaks for the hand-drawn look (wobbly outlines, hachure fills, à la Rough.js). Pass a sketch() value to any mark's ⁠sketch =⁠ argument, to an element_line() / element_rect() ⁠sketch =⁠ slot, or set it plot-wide with theme_sketch():

Details

vplot(mpg) |> mark_point(x = displ, y = hwy, sketch = sketch(roughness = 1.2))

Sketch is a geometry property, not a layer effect: it perturbs the mark itself (its wobble is generated natively in the vellum engine, so it is exact, cross-backend, and works in PDF), rather than compositing extra copies. Text is never sketched — pair a handwriting family with it for a fully hand-drawn plot.

Resolution is most-specific-wins: a mark's ⁠sketch =⁠ beats an element slot, which beats the plot-wide theme_sketch() default. At any level sketch = NA (or FALSE) forces that element crisp, overriding a broader default; sketch = NULL inherits.

Its arguments are the sketch parameters of vellum::sketch() — roughness, bowing, fill_style, fill_weight, hachure_angle, hachure_gap, curve_tightness, disable_multi_stroke, preserve_vertices, seed; see there for defaults. It returns a vellum_sketch object.

See Also

theme_sketch(), mark_point(), element_line()

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, sketch = sketch(roughness = 1.5, seed = 7))

Diagnose a spec against its data

Description

spec_diagnose() checks a spec (a list, JSON string, or path) or a built PlotSpec without throwing: it parses it, validates every referenced field against the data, runs a few pre-compile checks, dry-run compiles it, and reports per layer how many rows will not be shown. It returns a structured verdict. vplot_from_spec() is the strict form — it returns the PlotSpec on success and raises a classed vellumplot_spec_invalid error (carrying the same diagnostics) on failure.

Usage

spec_diagnose(spec, data = NULL, env = globalenv())

vplot_from_spec(spec, data = NULL, env = globalenv())

Arguments

spec

A spec list (from as_spec()), a JSON string, a .json path, or a PlotSpec.

data

The data frame the spec is drawn from. Required when the spec stores data by reference; optional (for field validation) when inlined. Ignored for a PlotSpec, which carries its own data.

env

Environment channel expressions are re-quoted in.

Details

This is the agent repair loop: a failure comes back as data an agent can act on (which field is unknown, the nearest real field) rather than a traceback.

Value

spec_diagnose() returns a list of class vellumplot_diagnosis with ok (logical), plot (the PlotSpec or NULL), diagnostics (a list of records with severity, field, message, hint), and report (a data frame with one row per layer: layer, mark, rows, the counts missing, transform, stat, limits, their total dropped, and oob, the rows outside a scale's limits that are still drawn; NULL when the plot could not be built). Printing it shows a summary. vplot_from_spec() returns a PlotSpec.

Pre-compile checks

Before compiling, the plot is checked for mistakes that would compile to a wrong plot or fail with an opaque error:

  • a facet variable missing from the plot data (an error), or from a layer's own data (a warning: that layer is then repeated across that variable's panels);

  • color (or fill) mapped to variables of different type in two layers (one continuous, one discrete), although the layers share one scale and legend (an error, or a warning when the scale kind is set explicitly);

  • a manual or discrete palette (scale_color_manual(), ...) on a continuous colour channel, which the compile refuses (an error).

Compile report

Some rows produce no visible mark. The report element counts them per layer, on the layer's input rows, attributing each row to the first reason that applies:

  • missing: a continuous position value (x, y, xend, ymin, ...) is NA. Such a row is removed from the plot with a warning, or leaves a gap in a line, step or area;

  • transform: the axis transform cannot map the value, e.g. a value ⁠<= 0⁠ on a log axis;

  • stat: the layer's statistic leaves the row out, e.g. an infinite value in a histogram or density, or a group with too few points for a density, a smooth or an ellipse;

  • limits: the value is outside explicit scale limits (lims(), ⁠scale_*(limits = )⁠), so it is clipped away. Coordinate limits (coord_cartesian(xlim = )) zoom instead and are not counted.

Their total is dropped. Limits follow each scale's oob handler: a position outside its limits counts under limits when it is clipped (the default) or censored, and so does a censored size. A separate column, oob, counts rows that are outside a scale's limits but still drawn: a squished position, or a colour, fill, size, alpha or linewidth value (clamped to the end of the palette, given the NA colour, or extrapolated). They are not part of dropped.

A missing non-position value (colour, size, ...) is drawn with the scale's NA value, a missing discrete position as a trailing "NA" category, and a missing facet value in a trailing "NA" panel, so none of them is counted. Each layer that loses rows also adds a "warning" diagnostic, so it shows in the printed summary.

See Also

spec_fields(), spec_schema(), vplot_ask()

Examples

spec <- as_spec(vplot(mtcars) |> mark_point(x = wt, y = mpg))
d <- spec_diagnose(spec, data = mtcars)
d$ok

# a PlotSpec works too; the report shows rows a log axis cannot draw
df <- data.frame(x = 1:4, y = c(-1, 1, 10, NA))
p <- vplot(df) |>
  mark_point(x = x, y = y) |>
  scale_y_continuous(trans = "log10")
spec_diagnose(p)

Summarise a data frame's fields for a model

Description

spec_fields() returns one row per column of data with its name, inferred encoding type (quantitative / nominal / ordinal / temporal), R class, distinct-value count, and a few example values. It is the grounding step for LLM plot generation (vplot_ask(), the MCP list_fields tool): handing a model the real vocabulary up front is what prevents hallucinated column names, and vplot_from_spec() then validates against exactly these.

Usage

spec_fields(data, n_examples = 3L)

Arguments

data

A data frame.

n_examples

How many example values to show per field (default 3).

Value

A data frame with columns name, type, class, n_unique, examples.

See Also

vplot_from_spec(), spec_schema()

Examples

spec_fields(mtcars)

The vellumplot spec JSON Schema

Description

Returns the bundled JSON Schema (Draft 2020-12) describing a serializable vellumplot spec — the input contract for spec_from_json() and the MCP render_spec / get_schema tools. An agent can validate a generated spec against it before rendering.

Usage

spec_schema(as = c("string", "list", "path"))

Arguments

as

A character scalar: "string" (raw JSON, the default), "list" (parsed R list), or "path" (the file path in the installed package).

Value

The schema as a string, a list, or a file path.

See Also

spec_to_json(), spec_fields()

Examples

schema <- spec_schema(as = "list")
schema$title

Serialize a plot to / from a JSON spec string

Description

spec_to_json() renders a PlotSpec as a JSON string (via as_spec()); spec_from_json() parses one back into a PlotSpec (via from_spec()). This is the portable wire format for the LLM / agent tooling and the Vega-Lite bridge. See as_spec() for the serializable subset and its guarantees.

Usage

spec_to_json(plot, pretty = TRUE)

spec_from_json(json, data = NULL, env = globalenv())

Arguments

plot

A PlotSpec.

pretty

Whether to pretty-print (default TRUE).

json

A JSON spec string (or a path to a .json file).

data, env

Passed to from_spec() — a data frame for a by-reference spec, and the environment channel expressions are re-quoted in.

Value

spec_to_json() returns a length-1 JSON string; spec_from_json() returns a PlotSpec.

See Also

as_spec(), spec_schema(), vplot_from_spec()

Examples

p <- vplot(mtcars) |> mark_point(x = wt, y = mpg)
json <- spec_to_json(p)
p2 <- spec_from_json(json)

Convert between a vellumplot spec and a Vega-Lite specification

Description

spec_to_vegalite() translates a PlotSpec into a Vega-Lite specification; spec_from_vegalite() translates one back. Both are layered grammars of graphics, so the mapping is direct for the common cases — marks, encodings, scales (domain / log-sqrt type / categorical range / title), bin + count, faceting, inline data, and the plot title.

Usage

spec_to_vegalite(plot, json = FALSE)

spec_from_vegalite(vl, data = NULL, env = globalenv())

Arguments

plot

A PlotSpec.

json

For spec_to_vegalite(), return a JSON string instead of a list.

vl

A Vega-Lite spec as a parsed list or a JSON string.

data

Optional data frame for a Vega-Lite spec whose data is external.

env

Environment channel expressions are re-quoted in (for spec_from_vegalite()).

Details

Free facet scales and resolve_scale() map to the facet's Vega-Lite resolve: an independent scale becomes resolve.scale, with its axis (x/y) or legend made independent too. On import, a facet-level resolve.scale comes back as the resolve lattice; an independent axis or legend over a shared scale, and a resolve between the layers of one view (e.g. a dual axis), have no vellumplot equivalent and are reported.

A continuous x or y scale whose data leaves zero out exports scale: {zero: false}, as Vega-Lite otherwise stretches a quantitative position axis to zero. A layer's ⁠tooltip =⁠ is Vega-Lite's tooltip channel: a column exports as that field, any other expression as the fields it reads (reported). On import, one tooltip field becomes that column, and an array of fields (or tooltip: true) a "title: value" line per field. Other interactive arguments (data_id, onclick, ...) are reported.

The bridge covers a documented subset (see the "Specs, agents, and interoperability" article). Anything it cannot map — polar/flipped coordinates, layer effects, patterns, statistical marks without a Vega-Lite equivalent — is reported via a warning listing the dropped features, never silently diverged.

Value

spec_to_vegalite() returns a Vega-Lite spec (a list, or JSON string if json = TRUE); spec_from_vegalite() returns a PlotSpec.

See Also

as_spec(), spec_to_json()

Examples

p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = cyl)
vl <- spec_to_vegalite(p)
vl$mark

Plot themes

Description

Control the non-data look of a plot. theme_gray() is the default (grey panel, white gridlines); theme_minimal() drops the panel fill for light gridlines on the page; theme_bw() is a white panel with light grey gridlines; theme_classic() has axis lines and no gridlines; theme_void() strips everything but the marks, legend, and titles; theme_cyberpunk() is a dark neon theme (see Details).

Usage

theme_gray(plot, base_size = 11, base_family = "")

theme_minimal(plot, base_size = 11, base_family = "")

theme_bw(plot, base_size = 11, base_family = "")

theme_classic(plot, base_size = 11, base_family = "")

theme_void(plot, base_size = 11, base_family = "")

theme_light(plot, base_size = 11, base_family = "")

theme_dark(plot, base_size = 11, base_family = "")

theme_linedraw(plot, base_size = 11, base_family = "")

theme_cyberpunk(plot, base_size = 11, base_family = "")

theme(plot, ...)

set_theme(
  plot,
  panel_bg = NULL,
  grid_col = NULL,
  label_col = NULL,
  strip_bg = NULL
)

Arguments

plot

A PlotSpec. theme() also accepts a PlotComposition, setting the figure-level chrome (title bands, collected legend, panel spacing, tags).

base_size

Base text size in points (default 11). Every text element is sized relative to it, so theme_gray(base_size = 14) scales titles, axis text, legend text and strips together.

base_family

Base font family for all text; "" (default) keeps the system default.

...

Named theme elements, e.g. plot.title = element_text(size = 16), panel.grid.minor = element_blank(), or settings like legend.position, one of "right" (default), "left", "top", "bottom", "none", or "inside". An inside legend sits over the panels at legend.position.inside = c(x, y) (fractions of the panel area; the older legend.position = c(x, y) works too), its legend.justification point (c(x, y) or words such as c("right", "top"), defaulting to the position) on that spot. Legends drawn beside each facet panel (guide_legend(position = "panel")) sit on the side legend.position names, justified along the panel edge by legend.justification (e.g. "top" aligns a legend right of a panel with the panel's top). geom = element_geom(ink, paper, accent) sets the default colours of unmapped marks (see element_geom()). Legend geometry is tunable via legend.key.size (key/swatch side, mm), legend.key.point.min (the smallest radius, mm, a point key of a layer with a constant size is drawn at, default 1 – an unsized point's radius – so tiny points keep readable keys; a size legend keeps its mapped sizes), legend.spacing (gap between stacked guides, mm), and legend.margin (inset around the legend block, one or four millimetres, ⁠t, r, b, l⁠).

panel_bg, grid_col, label_col, strip_bg

Colours (or NA to draw nothing) for the panel background, gridlines, axis-label/legend text, and facet strip background.

Details

theme() overrides individual elements on top of the current theme using element_text() / element_line() / element_rect() / element_blank(). set_theme() is a small back-compatible shortcut for the most common colours.

theme_cyberpunk() sets a dark canvas with dim neon gridlines and a bright neon default palette (both discrete and continuous), in the spirit of mplcyberpunk. It pairs with the glow() layer effect and linear_gradient() fills for the full neon look; the palette is only a default, so ⁠scale_*⁠ overrides still win. Unmapped marks draw in the light foreground colour (element_geom(ink = "#c7d0f0")), with smooths and contours in neon cyan.

Value

The modified PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg) |> theme_minimal()
vplot(mtcars) |>
  mark_point(x = wt, y = mpg) |>
  theme(panel.grid.minor = element_blank(), legend.position = "none")

# a legend tucked into the top-right corner of the panel
vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl)) |>
  theme(legend.position = "inside", legend.justification = c(1, 1))

Hand-drawn plot theme

Description

theme_sketch() turns a whole plot hand-drawn in one line: it sets a plot-wide sketch() default that every geometry mark and theme element inherits (wobbly gridlines, axis lines, ticks, and marks), on a warm paper-toned background. Text is never sketched — pass a handwriting font to complete the look.

Usage

theme_sketch(
  plot,
  roughness = 1,
  bowing = 1,
  fill_style = "hachure",
  seed = 1L,
  font = NULL,
  paper = "#f4ecd8",
  ink = "#2b2b2b"
)

Arguments

plot

A PlotSpec.

roughness, bowing, fill_style, seed

Passed to sketch() to build the plot-wide default (see sketch() for the full set of knobs).

font

Font family for all text (text is not sketched; a handwriting font such as "Comic Sans MS" or "Chilanka" sells the hand-drawn look). NULL (default) keeps the system default family.

paper, ink

Background and foreground (text/line) colours. Setting either also makes them the default mark colours (element_geom()), so unmapped marks draw in ink and fills mix ink with paper.

Details

It is a complete theme (like theme_cyberpunk()): the sketch it sets is only a default, so any mark's ⁠sketch =⁠ argument, any element_line() / element_rect() ⁠sketch =⁠ slot, or a ⁠scale_*⁠ override still wins. Force an individual element crisp with sketch = NA.

Value

The modified PlotSpec.

See Also

sketch(), theme_gray(), mark_point()

Examples

vplot(mtcars) |>
  mark_point(x = wt, y = mpg, color = factor(cyl)) |>
  theme_sketch()

# tune the wobble; a crosshatch-filled bar layer that stays crisp
df <- data.frame(g = c("a", "b", "c"), n = c(3, 5, 2))
vplot(df) |>
  mark_bar(x = g, y = n, fill = g) |>
  theme_sketch(roughness = 1.4, fill_style = "crosshatch", seed = 7)

Reveal a plot progressively along a variable

Description

transition_reveal() draws the data in, in the order of along – the classic "line draws itself" animation, as in gganimate. Each frame shows the rows whose along value has been reached: a point appears when the reveal reaches it, and a line, path, area, ribbon or step grows through its rows with an interpolated leading point, so it advances smoothly between data points rather than jumping from one to the next.

Usage

transition_reveal(plot, along)

Arguments

plot

A PlotSpec (from vplot()).

along

The variable the reveal follows: numeric, Date or POSIXct (often time, but any ordering column, such as a path's parameter).

Details

The reveal follows along, not the screen: a spiral revealed along its parameter winds outwards, a coord_flip() series grows up the vertical axis, and a reversed scale grows from the right. Only the data layers change; the panel background, gridlines, axes and legends are drawn whole on every frame, and the scales are trained once over all the data and frozen, so nothing moves as the data arrive. A layer whose own data lacks the along variable (a reference line, say) is drawn whole throughout.

animate(nframes = ) frames are spread evenly over the range of along (the ease_aes() position easing shapes the pace). Each frame is compiled from its own rows, so a statistic (a smooth) is recomputed on the data revealed so far. The leading point is interpolated on the data values, before any scale transformation, and among the rows of each group (the group aesthetic, else the layer's discrete colour/fill/linetype/... mappings).

Value

The modified PlotSpec.

See Also

transition_states(), transition_time(), animate()

Examples

vplot(data.frame(t = 1:20, y = cumsum(rnorm(20)))) |>
  mark_line(x = t, y = y) |>
  transition_reveal(t)

Animate a plot across the states of a variable

Description

transition_states() turns a plot into a keyframe animation: the plot is compiled once per level of states (a "keyframe"), and animate() tweens the frames between successive keyframes. The scales are trained once over all states and frozen, so axis breaks, colour ramps and sizes stay put across the whole animation (the interpolation is non-reactive: the states are fixed at author time, nothing retrains in response to anything).

Usage

transition_states(
  plot,
  states,
  transition_length = 1,
  state_length = 1,
  wrap = TRUE
)

Arguments

plot

A PlotSpec (from vplot()).

states

A column (bare or a string) whose distinct values, in level order, are the animation's states.

transition_length

Relative duration of the moving segments between states.

state_length

Relative duration of the held pause on each state.

wrap

Loop the last state back to the first?

Details

The step only records the intent; call animate() to build the animation and anim_save() to write it. A plain (non-animated) render ignores it.

Value

The modified PlotSpec.

See Also

ease_aes(), animate(), anim_save()

Examples

if (requireNamespace("gapminder", quietly = TRUE)) {
  library(gapminder)
  p <- vplot(gapminder) |>
    mark_point(x = gdpPercap, y = lifeExp, size = pop, color = continent) |>
    scale_x_continuous(trans = "log10") |>
    transition_states(year)
}

Animate a plot along a continuous time

Description

transition_time() is like transition_states() but treats time as a continuous quantity: the states are its distinct values and each transition is allocated frames in proportion to its time gap, so the animation plays at a constant rate through unevenly spaced times. There is no pause on a state and no wrap — time flows once, start to finish.

Usage

transition_time(plot, time)

Arguments

plot

A PlotSpec (from vplot()).

time

A numeric, Date or POSIXct column giving each row's time.

Details

{frame_time} in a title, subtitle or caption shows the time each frame has reached, updated on every frame (see Frame variables in animate()); for a Date or POSIXct time it is a Date or POSIXct, so "{format(frame_time, '%b %Y')}" works.

Value

The modified PlotSpec.

See Also

transition_states(), ease_aes(), animate()

Examples

if (requireNamespace("gapminder", quietly = TRUE)) {
  vplot(gapminder::gapminder) |>
    mark_point(x = gdpPercap, y = lifeExp, size = pop, color = continent) |>
    scale_x_continuous(trans = "log10") |>
    transition_time(year)
}

Chord diagram

Description

vchord() draws a weighted flow as a circular chord diagram: one arc (sector) per node, sized by the node's total incident weight, and one ribbon per flow joining a slice of the source sector to a slice of the target sector through the centre. Input is a flow list – from, to, value – or a square flow matrix (row = from, column = to; dimnames are the node names). Like vgraph() / vsankey() it returns a ready, axis-free, aspect-locked PlotSpec; mark_chord() is the layer it adds.

Usage

vchord(
  data,
  from,
  to,
  value,
  gap = 0.02,
  sort = c("input", "value"),
  link_color = c("source", "target"),
  direction = c("gradient", "gap", "both", "none"),
  label = TRUE,
  width = 6,
  height = 6,
  dpi = 96
)

mark_chord(
  plot,
  from,
  to,
  value,
  gap = 0.02,
  sort = c("input", "value"),
  link_color = c("source", "target"),
  direction = c("gradient", "gap", "both", "none"),
  label = TRUE
)

Arguments

data

A data frame of flows, or a square numeric matrix (row = from, column = to).

from, to, value

Columns (tidy-eval) for the data-frame form: the source node, target node, and flow weight. Omit for the matrix form.

gap

Gap between sectors, as a fraction of the circle each (default 0.02).

sort

Sector and ribbon order: "input" (default, first-appearance) or "value" (largest weight first).

link_color

Colour ribbons by their "source" (default) or "target" node.

direction

How to show a ribbon's direction: "gradient" (default, fade from opaque at the source to faint at the target), "gap" (stop the ribbon short of the target sector, leaving a small gap), "both", or "none".

label

Label each sector with its node name? Default TRUE.

width, height, dpi

Page size (inches) and resolution.

plot

A PlotSpec.

Details

Flows are directed: each node's arc splits into an outgoing block then an incoming block, so a -> b and b -> a are separate ribbons and a self-flow a -> a loops from the node's out-block to its own in-block. Sectors are coloured by node (a qualitative palette); ribbons take their source node's colour by default (link_color = "target" to colour by target).

Value

A PlotSpec (vchord()) or the modified plot (mark_chord()).

Examples

flows <- data.frame(
  from = c("A", "A", "B", "C"),
  to = c("B", "C", "C", "A"),
  value = c(3, 2, 4, 1)
)
vchord(flows, from, to, value)

Dendrogram from a clustering

Description

vdendrogram() turns a base hclust/dendrogram (e.g. from stats::hclust()) into a ready node-link dendrogram: leaves spread along a line, each merge drawn at its height, joined by right-angle brackets. It is a thin preset over ⁠vgraph(<clustering>, layout = "dendrogram")⁠ plus bracket edges and leaf labels; for full control, use that path and add marks yourself.

Usage

vdendrogram(
  x,
  direction = c("down", "up", "left", "right"),
  k = NULL,
  labels = TRUE,
  label_size = 5,
  width = 7,
  height = 5,
  dpi = 96
)

Arguments

x

An hclust or dendrogram object.

direction

Growth direction (leaves opposite the root): "down" (default; root at top), "up", "left", or "right".

k

Optionally cut the tree into k clusters (stats::cutree()) and colour branches and leaf labels by cluster; branches above the cut stay neutral. NULL (default) draws a single-colour tree.

labels

Draw the leaf labels? Default TRUE.

label_size

Leaf-label font size (points). Default 5; lower it for a tree with many leaves.

width, height, dpi

Page size (inches) and resolution.

Value

A PlotSpec.

See Also

vgraph() for the general node-link path (layout = "dendrogram" or "unrooted").

Examples

hc <- hclust(dist(USArrests))
vdendrogram(hc, k = 3)

Start a graph (network) plot

Description

vgraph() begins a node-link diagram from an igraph graph. It computes a layout (vertex x/y), builds a node table and an edge table, and returns a PlotSpec with the aspect locked (coord_equal) and a void theme (no axes or gridlines) – publication-quality defaults with no tuning. Add layers with mark_edges(), mark_nodes(), and mark_node_text(); edges default to the edge table and nodes to the node table.

Usage

vgraph(
  g,
  layout = "stress",
  ...,
  augment = FALSE,
  filter_nodes = NULL,
  filter_edges = NULL,
  k_core = NULL,
  seed = 42L,
  width = 6,
  height = 4,
  dpi = 96
)

Arguments

g

An igraph graph (or a two-column edge-list matrix).

layout

A layout: a name ("stress" (default), "sparse_stress", "backbone", "fr", "kk", "circle", "tree", "sugiyama", ...), a supplied ⁠N x 2⁠ coordinate matrix, or a function f(g, ...) returning one.

...

Extra arguments forwarded to the layout function (e.g. ⁠pivots =⁠ for sparse stress).

augment

Opt-in vertex metrics to attach as graph attributes (so they can be mapped – mark_nodes(size = degree) – or used by filter_nodes). FALSE (default) attaches nothing; TRUE attaches degree and components; a character vector picks from "degree", "in_degree", "out_degree", "betweenness", "closeness", "eigen", "coreness", "components", "community". Never computed silently – vellum does not guess which centrality you meant.

filter_nodes, filter_edges

Data-masked predicates that keep the vertices / edges for which they are TRUE, evaluated against the vertex / edge attribute table – e.g. filter_edges = weight > 0.5, filter_nodes = degree >= 2 (with augment). The graph is reduced before the layout, so the picture is of the subgraph, not a full layout with holes.

k_core

Keep only the k-core: vertices with coreness ⁠>= k_core⁠ (and their induced edges). NULL (default) keeps everything.

seed

Integer seed for stochastic layouts ("fr", "drl"), making the figure reproducible. The global RNG stream is restored afterwards.

width, height

Page size in inches.

dpi

Output resolution in dots per inch (see vplot()).

Details

The default layout is stress majorization (graphlayouts::layout_with_stress): it is deterministic (same graph -> same picture) and minimizes the difference between drawn and graph-theoretic distance. Above 10^4 nodes it falls back to sparse stress automatically. Reciprocal and parallel edges are drawn as parallel straight lines offset off the centre line (not curved); self-loops as small loops.

igraph (and graphlayouts, for its layouts) are optional dependencies (in Suggests); vgraph() errors with an install hint if they are not available.

Reductions apply in a fixed order: augment (metrics computed on the input graph) -> filter_edges -> filter_nodes -> k_core. Augmented metrics thus reflect the input graph, not the post-filter subgraph.

A graph can be faceted by a vertex attribute (facet_wrap(~group)): each panel draws that group's nodes and only the edges whose two endpoints are both in the panel, as ggraph's facet_nodes() does. Edges between groups are left out, and all panels share the one layout.

Value

A PlotSpec whose data is the node table and whose edge_data is the edge table.

See Also

mark_edges(), mark_nodes(), mark_node_text()

Examples

## Not run: 
g <- igraph::make_graph("Zachary")
vgraph(g, layout = "stress") |>
  mark_edges() |>
  mark_nodes(size = 3)

# attach degree, then plot only the 2-core, sized by degree
vgraph(g, augment = TRUE, k_core = 2) |>
  mark_edges() |>
  mark_nodes(size = degree)

## End(Not run)

Hierarchy diagrams: sunburst, icicle, treemap, circle-pack

Description

vhierarchy() draws a tree as a space-filling diagram, choosing the geometry with type: "sunburst" (concentric ring sectors), "icicle" (rectangular partition), "treemap" (squarified nested rectangles), or "circlepack" (circles within circles). All four take the same parent list — id, parent (NA/"" at the root), and value (leaf values; an internal node's value is the sum of its children) — so switching type re-encodes the same data. Like vgraph() / vsankey() it returns a ready, axis-free, aspect-locked PlotSpec; mark_hierarchy() is the layer it adds.

Usage

vhierarchy(
  data,
  id,
  parent,
  value,
  fill = NULL,
  type = c("sunburst", "icicle", "treemap", "circlepack"),
  inner_radius = 0,
  flow = c("down", "up", "right", "left"),
  lighten = 0.6,
  label = TRUE,
  show_values = FALSE,
  orientation = c("auto", "radial", "tangential", "horizontal"),
  root_label = FALSE,
  width = 6,
  height = 6,
  dpi = 96
)

mark_hierarchy(
  plot,
  id,
  parent,
  value,
  fill = NULL,
  type = c("sunburst", "icicle", "treemap", "circlepack"),
  inner_radius = 0,
  flow = c("down", "up", "right", "left"),
  lighten = 0.6,
  label = TRUE,
  show_values = FALSE,
  orientation = c("auto", "radial", "tangential", "horizontal"),
  root_label = FALSE
)

Arguments

data

A data frame describing a hierarchy (a parent list).

id, parent, value

Columns (tidy-eval): the node id, its parent id (NA/"" for the root), and its value (used for leaves).

fill

Optional column (tidy-eval) to colour nodes by. Unmapped (default), nodes are coloured by their depth-1 branch and lightened with depth; mapped, each node takes its fill value's colour with no depth fade.

type

Diagram geometry: "sunburst" (default), "icicle", "treemap", or "circlepack".

inner_radius

Sunburst only: central hole radius, a fraction in ⁠[0, 1)⁠; 0 (default) fills to the centre.

flow

Icicle only: the direction of increasing depth — "down" (default), "up", "right", or "left".

lighten

Branch mode only: how far the deepest level fades toward white, a fraction in ⁠[0, 1]⁠ (default 0.6; 0 = flat colour per branch). Ignored when fill is mapped.

label

Label each node with its id? Default TRUE. Nodes too small for their label are left unlabelled.

show_values

Append each node's value to its label, e.g. "A1 (3)". Default FALSE.

orientation

Sunburst labels only: "auto" (default) angles each label tangentially / radially to fit its wedge, or force "radial", "tangential", or "horizontal". Labels are kept upright.

root_label

Write the root's name (and, with show_values, its total) in the centre? Default FALSE. Most useful for "sunburst".

width, height, dpi

Page size (inches) and resolution.

plot

A PlotSpec.

Details

The root is structural and never drawn (in a sunburst it is the centre). Each node is labelled with its id where the label fits, and show_values appends the value; small nodes are left unlabelled so a dense diagram stays legible.

Value

A PlotSpec (vhierarchy()) or the modified plot (mark_hierarchy()).

Colour

By default nodes are coloured by their depth-1 branch and lightened one step per level, so sibling branches stay distinct and depth reads as shade. The branch is an ordinary discrete fill scale, so ⁠scale_fill_*()⁠ recolours the branches (e.g. scale_fill_brewer()), and lighten controls the depth fade (0 = flat colour per branch). Map fill to a node column instead to colour every node by that variable — discrete or continuous, with the matching ⁠scale_fill_*()⁠ — in which case the depth fade is not applied.

Examples

h <- data.frame(
  id = c("root", "A", "B", "A1", "A2", "B1"),
  parent = c(NA, "root", "root", "A", "A", "B"),
  value = c(NA, NA, NA, 3, 2, 4)
)
vhierarchy(h, id, parent, value, show_values = TRUE)
vhierarchy(h, id, parent, value, type = "treemap")

Custom tiling-pattern fill

Description

vl_pattern() is vellum::vl_pattern(), re-exported, for building a pattern fill from an arbitrary tile grob when the ready-made pattern_stripe() family does not fit. Like a gradient, the result (a vellum_pattern object) is an unscaled fill value. It takes the tile grob, the tile width / height and anchor x / y in units, and extend; see vellum::vl_pattern() for the full reference.

See Also

pattern_stripe(), linear_gradient()

Examples

dots <- vellum::circle_grob(r = 0.25, gp = vellum::vl_gpar(fill = "grey30"))
vl_pattern(dots, width = 0.08, height = 0.08)

Start a plot specification

Description

vplot() begins a declarative, pipe-first plot. It captures the data and page size and returns an inspectable PlotSpec; nothing is drawn until the spec is compiled (via render_plot() or vellum::as_vellum_scene()). Build the plot up with mark_point() / mark_line() / mark_rule() and the ⁠scale_*()⁠ functions.

Usage

vplot(data, width = 6, height = 4, dpi = 96)

Arguments

data

A data frame. Encoding expressions in ⁠mark_*()⁠ are evaluated against it with tidy evaluation.

width, height

Page size in inches.

dpi

Output resolution in dots per inch. The exported PNG's pixel dimensions are width * dpi by height * dpi; raising dpi yields a denser image at the same physical size. Overridable at render time via render_plot()'s dpi argument.

Value

A PlotSpec.

Examples

vplot(mtcars) |> mark_point(x = wt, y = mpg)

Generate a plot from a natural-language request

Description

vplot_ask() is a thin, model-agnostic convenience: it assembles the grounding payload (the JSON spec_schema() plus spec_fields() for data and the user's prompt), hands it to a responder function you supply — any function that takes the payload and returns a JSON spec string (wrapping the Claude API, an MCP client, a local model, or a canned fixture) — and validates the result with vplot_from_spec().

Usage

vplot_ask(prompt, data, responder, env = globalenv())

Arguments

prompt

A natural-language description of the desired plot.

data

The data frame to plot.

responder

A function ⁠function(payload) -> json_string⁠. payload is a list with prompt, fields (from spec_fields()), and schema.

env

Environment channel expressions are re-quoted in.

Details

vellumplot deliberately ships no built-in model client: the value is the schema, the grounding, and the validated repair loop, not a hard dependency on one provider. For a ready-to-run agent integration, point an MCP client at the bundled server (system.file("mcp/server.R", package = "vellumplot")).

Value

A PlotSpec.

See Also

spec_fields(), vplot_from_spec(), spec_schema()

Examples

# a canned responder standing in for a model call:
responder <- function(payload) {
  spec_to_json(vplot(mtcars) |> mark_point(x = wt, y = mpg))
}
p <- vplot_ask("scatter of weight vs mpg", mtcars, responder)

Sankey (flow) diagram

Description

vsankey() draws a layered flow diagram from a flow list — one row per flow with a from node, a to node, and a value (the ribbon width). Nodes are the union of from/to; a node that is both a source and a target makes the diagram multi-stage. Like vgraph(), it returns a ready PlotSpec with an axis-free, aspect-free panel; mark_sankey() is the layer it adds and can be used directly on a plot you have set up yourself.

Usage

vsankey(
  data,
  from,
  to,
  value,
  label = TRUE,
  show_values = FALSE,
  flow_color = "source",
  node_width = 0.04,
  node_gap = 0.02,
  width = 8,
  height = 5,
  dpi = 96
)

mark_sankey(
  plot,
  from,
  to,
  value,
  label = TRUE,
  show_values = FALSE,
  flow_color = "source",
  node_width = 0.04,
  node_gap = 0.02
)

Arguments

data

A data frame of flows.

from, to, value

Columns (tidy-eval): the source node, target node, and flow value.

label

Draw node labels? Default TRUE.

show_values

Append each node's value to its label (e.g. "Grid (60)")? Default FALSE. Ignored when label = FALSE.

flow_color

Ribbon fill: "source" (default) colours each ribbon by its source node, "target" by its target node, and "gradient" fades each ribbon from its source colour to its target colour.

node_width

Node-rectangle width, as a fraction of the plotting width (default 0.04).

node_gap

Vertical gap between the nodes in a column, as a fraction of the column height (default 0.02).

width, height, dpi

Page size (inches) and resolution.

plot

A PlotSpec.

Details

The flows must form a DAG (no cycles). Nodes within a column are ordered to minimise ribbon crossings (a deterministic Sugiyama barycenter sweep), and ribbons are stacked to meet each node in matching order. Nodes are coloured from the built-in qualitative palette.

Value

A PlotSpec (vsankey()) or the modified plot (mark_sankey()).

Examples

flows <- data.frame(
  from = c("A", "A", "B", "C", "C"),
  to = c("B", "C", "D", "D", "E"),
  value = c(4, 6, 4, 4, 2)
)
vsankey(flows, from, to, value)
vsankey(flows, from, to, value, show_values = TRUE, flow_color = "target")

Sparklines — tiny word-sized charts

Description

vsparkline() builds a compact, axis-free chart of a single numeric series, sized in physical units (mm by default) so it reads as a word-sized graphic (Tufte's sparkline) — for a table cell, a caption, or a dashboard tile. It is a self-contained PlotSpec: render it with render_plot(), drop it into a composition with inset(), or (soon) a table cell.

Usage

vsparkline(
  values,
  type = c("line", "bar", "winloss"),
  color = NULL,
  points = c("extremes", "last", "none"),
  point_color = NULL,
  baseline = 0,
  win_color = NULL,
  loss_color = "#d7301f",
  linewidth = 1,
  point_size = 1.4,
  width = 20,
  height = 6,
  units = "mm",
  dpi = 96
)

Arguments

values

A numeric vector (the series), length >= 2.

type

"line" (default), "bar", or "winloss".

color

Trend / bar colour. NULL (the default) is the theme's col_mix(ink, paper, 0.3): "grey30" on a light theme, a light grey on a dark one such as theme_cyberpunk().

points

For type = "line", which points get a dot: "extremes" (default – the min and max), "last", or "none".

point_color

Dot colour. NULL (the default) is the theme's accent colour (element_geom()), else "firebrick".

baseline

For "bar", the value bars grow from (default 0); for "winloss", the threshold separating a win (>=) from a loss (default 0).

win_color, loss_color

For "winloss", the up / down bar colours. win_color = NULL (the default) is the theme's accent colour, else blue; loss_color defaults to red.

linewidth

Trend line width (default 1).

point_size

Dot diameter in mm (default 1.4).

width, height, units

Physical size of the sparkline; units is one of "mm" (default), "cm", "in", "pt". Default ⁠20 x 6⁠ mm.

dpi

Resolution for raster output.

Details

Three shapes via type: a "line" trend (with optional dots on its extremes or last point), a "bar" column micro-chart, and a "winloss" chart of equal up/down bars about a baseline (for streaks of wins/losses, gains/drops).

The chart fills its box with no axes, gridlines, labels, or legend.

Value

A PlotSpec.

See Also

render_plot(), inset()

Examples

set.seed(1)
vsparkline(cumsum(rnorm(30)))
vsparkline(rpois(20, 5), type = "bar")
vsparkline(sample(c(-1, 1), 20, replace = TRUE), type = "winloss")

Tables with sparkline columns

Description

vtable() lays a data frame out as a grid of cells where an ordinary column renders as text and a list-column of numeric vectors renders as a per-row vsparkline() — chart-in-table, drawn as one vector scene (so it renders on PNG / SVG / PDF like any plot). It returns a compiled object; render_plot() it, print() it, or drop it into a composition.

Usage

vtable(
  data,
  spark = list(),
  cols = NULL,
  align = NULL,
  header = TRUE,
  font_size = 9,
  spark_width = 24,
  row_height = 7,
  cell_pad = 1.5,
  units = "mm",
  dpi = 96
)

Arguments

data

A data frame. Sparkline columns must be list-columns whose cells are numeric vectors.

spark

A named list mapping a (list-)column name to how it draws: a type string ("line"/"bar"/"winloss") or a function ⁠function(values)⁠ returning a vsparkline().

cols

Character vector of columns to show, in order (default all).

align

Optional named list of per-column alignment ("left"/"right"/"centre"); defaults to right for numeric, left otherwise.

header

Draw a bold header row with an underline (default TRUE).

font_size

Text size in points (default 9).

spark_width

Width of a sparkline column, in units (default 24).

row_height

Row height, in units (default 7).

cell_pad

Horizontal padding inside a text cell, in units (default 1.5).

units

Length unit for the sizes above: "mm" (default), "cm", "in", "pt".

dpi

Resolution for raster output.

Value

A VTable (renders via render_plot()).

See Also

vsparkline()

Examples

df <- data.frame(name = c("A", "B", "C"), mean = c(3.1, 5.4, 2.2))
df$trend <- list(cumsum(rnorm(20)), cumsum(rnorm(20)), cumsum(rnorm(20)))
vtable(df, spark = list(trend = "line"))

Venn / Euler diagrams

Description

vvenn() draws a Venn diagram of 2 or 3 sets: overlapping circles whose disjoint regions are filled by how many elements fall in exactly that combination of sets. Each region is drawn as solid geometry (via vellum::vl_path_op()'s boolean set operations), so overlapping regions do not alpha-composite and stay crisp — including in PDF, where a rasterised mask would degrade.

Usage

vvenn(sets, width = 5, height = 5, dpi = 96)

Arguments

sets

Either a named list of member vectors (list(A = ..., B = ...)), or a data frame of logical membership columns (each column is a set; TRUE means that row is a member). 2 or 3 sets.

width, height, dpi

Figure size (inches) and resolution.

Value

A PlotSpec; print or render_plot() it.

Examples

vvenn(list(
  Coffee = c("Ann", "Bo", "Cy", "Di"),
  Tea = c("Bo", "Di", "Ed", "Fi")
))

Waffle chart

Description

vwaffle() draws a waffle (square pie): a grid of cells coloured by category, where each category takes a share of the cells proportional to its count — a part-of-whole chart that is easier to read than a pie because the eye counts squares. It is a self-contained chart (like vsankey() / vvenn()): it returns a PlotSpec with no axes.

Usage

vwaffle(
  data,
  category,
  value = NULL,
  n_cells = 100,
  rows = 10,
  flip = FALSE,
  pad = 0.12,
  width = 5,
  height = 5,
  dpi = 96
)

Arguments

data

A data frame.

category

The categorical column that colours the cells (tidy-eval).

value

Optional per-row weight column; if omitted, each row counts once.

n_cells

Total number of cells in the grid (default 100). Each category gets round(share * n_cells) cells.

rows

Number of rows in the grid (default 10); cells fill column by column from the bottom-left.

flip

Fill row by row (left to right) instead of column by column.

pad

Gap between cells, as a fraction of a cell (default 0.12).

width, height, dpi

Page size (inches) and resolution for the standalone chart.

Details

Cells take the fill scale's colours. A cell with no fill colour falls back to "grey50", or to col_mix(ink, paper, 0.2) ("grey20") on a theme whose panel is that grey, such as theme_dark(), so it stays visible.

Value

A PlotSpec.

See Also

vvenn(), mark_pie()

Examples

df <- data.frame(part = c("a", "b", "c"), n = c(50, 30, 20))
vwaffle(df, category = part, value = n)