| 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 |
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()).
add_marginal( plot, type = c("density", "histogram"), sides = "tr", size = 0.15, adjust = 1, bins = 30, group = FALSE )add_marginal( plot, type = c("density", "histogram"), sides = "tr", size = 0.15, adjust = 1, bins = 30, group = FALSE )
plot |
|
type |
The marginal distribution: |
sides |
Which edges to draw, as a string of |
size |
The marginal size as a fraction of the panel, in |
adjust |
Bandwidth multiplier for |
bins |
Number of bins for |
group |
When |
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.
The modified PlotSpec.
mark_density(), mark_histogram(), facet_wrap()
vplot(faithful) |> mark_point(x = eruptions, y = waiting) |> add_marginal() vplot(faithful) |> mark_point(x = eruptions, y = waiting) |> add_marginal(type = "histogram", sides = "t")vplot(faithful) |> mark_point(x = eruptions, y = waiting) |> add_marginal() vplot(faithful) |> mark_point(x = eruptions, y = waiting) |> add_marginal(type = "histogram", sides = "t")
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).
add_selection(plot, selection)add_selection(plot, selection)
plot |
A PlotSpec. |
selection |
A |
The PlotSpec, with the selection registered.
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).
after_stat(x)after_stat(x)
x |
An expression in terms of the stat's computed variables. |
Its argument (the marker is interpreted at compile time).
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.
anim_frame(filename, animation, frame = NULL, scale = 1)anim_frame(filename, animation, frame = NULL, scale = 1)
filename |
Output path; |
animation |
A |
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,
|
scale |
Resolution multiplier (default 1), as in |
Frames are numbered as in the files anim_save() writes, pauses and rewind
included (see animate()).
filename, invisibly.
## 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)## 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)
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:
anim_save(filename, animation)anim_save(filename, animation)
filename |
Output path; |
animation |
A |
.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).
filename, invisibly.
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").
## 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)## 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)
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.
animate( plot, nframes = 50, fps = 25, start_pause = 0, end_pause = 0, rewind = FALSE )animate( plot, nframes = 50, fps = 25, start_pause = 0, end_pause = 0, rewind = FALSE )
plot |
A PlotSpec with a |
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: |
rewind |
Play the animation backwards after it has played forwards, so
the loop returns to its start smoothly instead of cutting (default
|
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).
A vellum_animation.
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
its data_id, when the layer declares one (mark_point(data_id = country)): the way to follow individual observations;
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;
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.
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.
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.
transition_states(), ease_aes(), anim_save(), anim_frame()
## 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)## 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)
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".
annotate( plot, geom, x = NULL, y = NULL, xend = NULL, yend = NULL, xmin = NULL, xmax = NULL, ymin = NULL, ymax = NULL, label = NULL, ... )annotate( plot, geom, x = NULL, y = NULL, xend = NULL, yend = NULL, xmin = NULL, xmax = NULL, ymin = NULL, ymax = NULL, label = NULL, ... )
plot |
A PlotSpec. |
geom |
The annotation geometry: one of |
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. |
"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().
The modified PlotSpec.
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)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)
design =
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.
area(t, l, b = t, r = l)area(t, l, b = t, r = l)
t, l, b, r
|
Top, left, bottom, right cell indices (1-based, inclusive). |
An area spec.
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)))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)))
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()).
as_spec(plot) from_spec(spec, data = NULL, env = globalenv())as_spec(plot) from_spec(spec, data = NULL, env = globalenv())
plot |
A PlotSpec. |
spec |
A spec list from |
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 |
env |
The environment channel expressions are re-quoted in (default the global environment). |
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.
as_spec() returns a named list; from_spec() returns a PlotSpec.
spec_to_json(), spec_to_vegalite(), vplot_from_spec()
p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = cyl) spec <- as_spec(p) spec$layers[[1]]$mark p2 <- from_spec(spec)p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = cyl) spec <- as_spec(p) spec$layers[[1]]$mark p2 <- from_spec(spec)
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().
bi_class(data, x, y, dim = 3, style = "quantile", name = "bi_class")bi_class(data, x, y, dim = 3, style = "quantile", name = "bi_class")
data |
A data frame or |
x, y
|
The two numeric variables (bare column names). |
dim |
Classes per variable: |
style |
How to choose the class breaks: |
name |
Name of the new column (default |
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.
data with a factor column name whose levels are all dim^2
classes in order. Rows where x or y is missing get NA.
scale_fill_bivariate(), bi_pal()
Other bivariate:
bi_pal(),
guide_bivariate(),
scale_fill_bivariate()
d <- bi_class(mtcars, hp, wt) table(d$bi_class)d <- bi_class(mtcars, hp, wt) table(d$bi_class)
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.
bi_pal(palette = "DkBlue", dim = 3)bi_pal(palette = "DkBlue", dim = 3)
palette |
A palette name: |
dim |
Classes per variable: |
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.
A named character vector of dim^2 colours.
bi_class(), scale_fill_bivariate()
Other bivariate:
bi_class(),
guide_bivariate(),
scale_fill_bivariate()
bi_pal("GrPink") bi_pal("DkBlue", dim = 2)bi_pal("GrPink") bi_pal("DkBlue", dim = 2)
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.
bind_scale(plot, selection, aes = c("x", "y"))bind_scale(plot, selection, aes = c("x", "y"))
plot |
A PlotSpec (the detail view). |
selection |
A |
aes |
The axis to bind, |
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.
The PlotSpec, with the bind registered.
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) )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) )
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).
clip_to(plot, region, invert = FALSE) clip_layer(plot, region, invert = FALSE) set_mask(plot, region = NULL, type = c("luminance", "alpha"), feather = 0.35)clip_to(plot, region, invert = FALSE) clip_layer(plot, region, invert = FALSE) set_mask(plot, region = NULL, type = c("luminance", "alpha"), feather = 0.35)
plot |
A PlotSpec. |
region |
The clip geometry: an |
invert |
For |
type |
For |
feather |
For |
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.
The modified PlotSpec.
## 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)## 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)
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).
compose_annotation( plot, title = NULL, subtitle = NULL, caption = NULL, tag_levels = NULL, tag_prefix = "", tag_suffix = "" )compose_annotation( plot, title = NULL, subtitle = NULL, caption = NULL, tag_levels = NULL, tag_prefix = "", tag_suffix = "" )
plot |
|
title, subtitle, caption
|
Figure-level text (or |
tag_levels |
Auto-tag style: |
tag_prefix, tag_suffix
|
Strings wrapped around each tag. |
The modified PlotComposition.
theme(), which also accepts a composition to set the figure-level
chrome (title bands, collected legend, panel spacing, tags).
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")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")
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).
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)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)
... |
PlotSpecs or |
ncol, nrow
|
Grid dimensions for |
byrow |
Fill the grid by row (default) or by column. |
widths, heights
|
Relative panel sizes per column / row (recycled numeric
vector), or |
guides |
|
design |
An explicit layout: a list of |
width, height
|
Output size in inches (defaults scale with the grid). |
dpi |
Output resolution in dots per inch. |
plots |
A list of PlotSpecs / |
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().
A PlotComposition (renders via render_plot() / vellum::render()).
a <- vplot(mtcars) |> mark_point(x = wt, y = mpg) b <- vplot(mtcars) |> mark_histogram(x = mpg, bins = 10) hconcat(a, b)a <- vplot(mtcars) |> mark_point(x = wt, y = mpg) b <- vplot(mtcars) |> mark_histogram(x = mpg, bins = 10) hconcat(a, b)
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.
condition(selection, if_true, if_false, empty = TRUE)condition(selection, if_true, if_false, empty = TRUE)
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 |
empty |
Whether an empty selection matches all elements ( |
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.
Used only inside a mark_*() encoding; not called directly.
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.
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)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)
plot |
A PlotSpec. |
xlim, ylim
|
Length-2 view-window limits, or |
ratio |
Aspect ratio for |
The modified PlotSpec.
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()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()
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().
coord_polar(plot, theta = "x", start = 0, direction = 1) coord_radial( plot, theta = "x", start = 0, end = NULL, direction = 1, inner_radius = 0 )coord_polar(plot, theta = "x", start = 0, direction = 1) coord_radial( plot, theta = "x", start = 0, end = NULL, direction = 1, inner_radius = 0 )
plot |
A PlotSpec. |
theta |
Which position aesthetic drives the angle: |
start |
Angular offset of the zero position, in radians ( |
direction |
Winding direction: |
end |
Arc end angle in radians; |
inner_radius |
Radius of the central hole as a fraction of the outer
radius ( |
The modified PlotSpec.
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)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)
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.
coord_sf( plot, crs = NULL, xlim = NULL, ylim = NULL, graticule = FALSE, graticule_labels = TRUE )coord_sf( plot, crs = NULL, xlim = NULL, ylim = NULL, graticule = FALSE, graticule_labels = TRUE )
plot |
A PlotSpec. |
crs |
Target coordinate reference system to project all layers into
(anything |
xlim, ylim
|
Length-2 view-window limits in the target CRS, or |
graticule |
Draw meridians and parallels behind the map. |
graticule_labels |
Label the graticule lines with their degree values
(default |
sf is an optional dependency (in Suggests); coord_sf() errors with an
install hint if it is not available at render time.
The modified PlotSpec.
mark_sf(), mark_scalebar(), mark_compass()
## 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)## 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)
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.
coord_trans(plot, x = "identity", y = "identity")coord_trans(plot, x = "identity", y = "identity")
plot |
A PlotSpec. |
x, y
|
Display transform for that axis (default |
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").
The modified PlotSpec.
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> coord_trans(y = "log10")vplot(mtcars) |> mark_point(x = wt, y = mpg) |> coord_trans(y = "log10")
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.
ease_aes( plot, ease = "linear", position = NULL, color = NULL, size = NULL, alpha = NULL, colour = NULL )ease_aes( plot, ease = "linear", position = NULL, color = NULL, size = NULL, alpha = NULL, colour = NULL )
plot |
A PlotSpec carrying a |
ease |
An easing name: |
position, color, size, alpha
|
Optional per-class easings, named the same way
as
|
colour |
An alias for |
The modified PlotSpec.
transition_states(), animate()
# 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")# 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")
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.
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()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()
family, face, size, cex, colour, color, hjust, vjust, angle, lineheight, margin
|
Text properties. |
linewidth, linetype, lineend
|
Line properties. |
sketch |
For |
fill |
Fill colour (rectangles). |
An element object for use in theme().
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> theme(plot.title = element_text(size = 16), panel.grid.minor = element_blank())vplot(mtcars) |> mark_point(x = wt, y = mpg) |> theme(plot.title = element_text(size = 16), panel.grid.minor = element_blank())
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.
element_geom( ink = NULL, paper = NULL, accent = NULL, colour = NULL, color = NULL, fill = NULL )element_geom( ink = NULL, paper = NULL, accent = NULL, colour = NULL, color = NULL, fill = NULL )
ink |
Foreground colour of marks (default |
paper |
Background colour marks are mixed against (default |
accent |
Colour of fitted smooths and contour lines (default
|
colour, color
|
A colour for every unmapped mark stroke, overriding the
colour derived from |
fill |
A fill for every unmapped filled mark, overriding the fill
derived from |
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.
An element object for the geom slot of theme().
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") )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_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.
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 )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 )
plot |
A PlotSpec. |
facets |
A faceting formula. For |
ncol, nrow
|
Number of columns/rows for |
scales |
One of |
labeller |
How to label the facet strips: a labeller such as
|
The modified PlotSpec.
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)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)
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.
filter_by(plot, selection)filter_by(plot, selection)
plot |
A PlotSpec. |
selection |
A |
The PlotSpec, with the filter registered.
select_interval(), add_selection()
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().
glow(size = 6, layers = 6L, alpha = 0.12, blend = "screen", color = NULL)glow(size = 6, layers = 6L, alpha = 0.12, blend = "screen", color = NULL)
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: |
alpha |
Base halo opacity (scaled by |
color |
Halo colour, or |
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.
A GlowSpec object for a mark's effects list.
outline(), shadow(), theme_cyberpunk()
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()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()
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).
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.
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))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))
gt tablegt_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).
gt_vsparkline( gt_object, column, type = "line", ..., width = 30, height = 8, units = "mm" )gt_vsparkline( gt_object, column, type = "line", ..., width = 30, height = 8, units = "mm" )
gt_object |
A |
column |
The list-column to render (bare name or string). |
type |
Sparkline type: |
... |
Further |
width, height, units
|
Sparkline size (default |
The vectors are recovered from the gt object's data in its current row order;
apply gt_vsparkline() before any gt row reordering / grouping.
The modified gt object.
vsparkline(), vtable(), plot_svg()
## 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)## 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)
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.
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 )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 )
title |
The axis title, or |
check.overlap |
If |
angle |
The rotation of the labels in degrees (overrides the theme's
|
n.dodge |
The number of rows (x) or columns (y) to stagger the labels
over, so neighbours alternate between them (default |
minor.ticks |
If |
cap |
Cap the axis line (theme element |
long, mid, short
|
Lengths of the ticks at 10^k, 5 x 10^k and the other
multiples, relative to the theme's |
prescale.base |
The base the data were already log-transformed with
(e.g. |
A guide specification for guides() or a scale's guide.
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"))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"))
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.
guide_bins( title = NULL, show.limits = FALSE, reverse = FALSE, axis = TRUE, position = NULL )guide_bins( title = NULL, show.limits = FALSE, reverse = FALSE, axis = TRUE, position = NULL )
title |
The legend title, or |
show.limits |
Also label the outer limits of the first and last bins
(default |
reverse |
Reverse the order of the keys. |
axis |
Draw the axis line and ticks beside the keys (default |
position |
Where this legend goes: |
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.
A guide specification for guides() or a scale's guide.
guides(), guide_coloursteps() for a binned colour scale as a
segmented bar.
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")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")
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.
guide_bivariate( title = NULL, xlab = NULL, ylab = NULL, key.size = NULL, labels = TRUE, rotate = FALSE, position = NULL )guide_bivariate( title = NULL, xlab = NULL, ylab = NULL, key.size = NULL, labels = TRUE, rotate = FALSE, position = NULL )
title |
A title above the grid, or |
xlab, ylab
|
The axis titles, or |
key.size |
Side of one swatch, in millimetres. |
labels |
Label the swatch edges with the class breaks |
rotate |
Turn the grid 45 degrees, so the classes read as a diamond
with high-high at the top (default |
position |
Where this legend goes: |
A guide specification for guides().
Other bivariate:
bi_class(),
bi_pal(),
scale_fill_bivariate()
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))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))
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.
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 )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 )
plot |
A PlotSpec. |
... |
Named by aesthetic, e.g. |
title |
An axis/legend title override, or |
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: |
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. |
position |
Where this legend goes: |
barwidth, barheight
|
The colour bar's own width and height, in millimetres
( |
ticks |
Draw the break ticks on the colour bar? (Default |
ticks.colour |
Colour of the break ticks (default |
label.position |
Which side of a vertical colour bar the labels sit,
|
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 There is deliberately no |
guides(): the modified PlotSpec. guide_none() / guide_legend():
a guide specification for use inside guides().
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"))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"))
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).
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 )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 )
base |
A PlotSpec or |
plot |
The PlotSpec to overlay. |
left, bottom, right, top
|
Inset position as fractions (0–1). |
align_to |
Reference box: |
on_top |
Draw the inset above ( |
shadow |
Optional drop shadow cast by the inset, from
|
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().
A PlotComposition.
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)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)
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.
inspect_source(plot, on = c("click", "hover"), values = FALSE)inspect_source(plot, on = c("click", "hover"), values = FALSE)
plot |
A PlotSpec. |
on |
The gesture that reveals the source, |
values |
If |
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.
The PlotSpec, with source inspection registered.
provenance_payload(), select_point()
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> inspect_source()vplot(mtcars) |> mark_point(x = wt, y = mpg) |> inspect_source()
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.
interaction_model(x)interaction_model(x)
x |
A PlotSpec or a plot composition. |
A named list (selections, conditions, filters, binds, and
source when inspect_source() is declared), or NULL if there is no
declared interactivity.
Labellers turn facet values into the text of the facet strips. Pass one as
the labeller argument of facet_wrap() or facet_grid().
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)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)
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 ( |
sep |
For |
width |
For |
x |
For |
default |
For |
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 ", ".
label_value() and label_both() return a list of character
vectors. label_wrap_gen() and as_labeller() return a labeller
function.
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))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))
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.
labs( plot, title = NULL, subtitle = NULL, caption = NULL, tag = NULL, x = NULL, y = NULL, color = NULL, colour = NULL, fill = NULL, size = NULL, alt = NULL, ... )labs( plot, title = NULL, subtitle = NULL, caption = NULL, tag = NULL, x = NULL, y = NULL, color = NULL, colour = NULL, fill = NULL, size = NULL, alt = NULL, ... )
plot |
A PlotSpec. |
title, subtitle, caption, tag
|
Plot-level text (or |
x, y, size
|
Axis / legend title overrides for those aesthetics. |
color, colour
|
Colour-scale title override; |
fill |
Fill-scale title override. |
alt |
A text alternative (alt text) describing the plot for screen
readers and other assistive technology. Overrides the description vellumplot
generates automatically; see |
... |
Reserved; passing anything here is an error. |
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.
The modified PlotSpec.
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> labs(title = "Fuel economy", x = "Weight", y = "MPG")vplot(mtcars) |> mark_point(x = wt, y = mpg) |> labs(title = "Fuel economy", x = "Weight", y = "MPG")
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.
lims(plot, ...) xlim(plot, ...) ylim(plot, ...)lims(plot, ...) xlim(plot, ...) ylim(plot, ...)
plot |
A PlotSpec. |
... |
For |
The modified PlotSpec.
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))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))
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.
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 )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 )
plot |
A PlotSpec. |
distance |
Bar length in |
unit |
Distance unit for the label and |
position |
Panel corner to anchor the decoration:
|
segments |
Number of alternating segments in the bar (default |
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 |
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 |
The modified PlotSpec.
## 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)## 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)
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.
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 )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 )
plot |
A PlotSpec. |
... |
For |
position |
Position adjustment; see |
slope, intercept
|
For |
blend, sketch, data
|
See |
fun |
For |
n |
For |
args |
For |
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
For |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
direction |
For |
auto |
For |
effects |
A list of layer render effects applied to the mark at draw
time — |
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).
The modified PlotSpec.
vplot(pressure) |> mark_area(x = temperature, y = pressure)vplot(pressure) |> mark_area(x = temperature, y = pressure)
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().
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
orientation |
For |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
width |
For |
fun |
For |
fun.data |
For |
fun.min, fun.max
|
For |
fun.args |
For |
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().
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
bins |
Target number of contour levels (when neither |
binwidth |
Spacing between contour levels, or |
breaks |
Explicit contour levels, or |
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
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
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.
The modified PlotSpec.
vplot(faithful) |> mark_point(x = eruptions, y = waiting) |> mark_contour(x = eruptions, y = waiting) vplot(faithful) |> mark_contour_filled(x = eruptions, y = waiting)vplot(faithful) |> mark_point(x = eruptions, y = waiting) |> mark_contour(x = eruptions, y = waiting) vplot(faithful) |> mark_contour_filled(x = eruptions, y = waiting)
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.
mark_count( plot, ..., position = "identity", blend = NULL, sketch = NULL, data = NULL )mark_count( plot, ..., position = "identity", blend = NULL, sketch = NULL, data = NULL )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
The modified PlotSpec.
vplot(mpg <- data.frame(cyl = mtcars$cyl, gear = mtcars$gear)) |> mark_count(x = cyl, y = gear)vplot(mpg <- data.frame(cyl = mtcars$cyl, gear = mtcars$gear)) |> mark_count(x = cyl, y = gear)
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.
mark_datashade( plot, ..., position = "identity", width = 400, height = 300, colors = NULL, how = "eq_hist", span = NULL, clip = NULL, spread = NULL, blend = NULL, data = NULL )mark_datashade( plot, ..., position = "identity", width = 400, height = 300, colors = NULL, how = "eq_hist", span = NULL, clip = NULL, spread = NULL, blend = NULL, data = NULL )
plot |
|
... |
Encodings; |
position |
Position adjustment: a string — |
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 |
how |
Density-to-colour mapping (and, categorically, per-cell opacity):
|
span, clip
|
Optional density-range clamping passed to |
spread |
Optional post-aggregation spreading to keep sparse output
visible (passed to |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
data |
Optional layer data frame; overrides the plot data for this layer. |
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.
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
contour_var |
The variable to contour: |
bins |
Target number of contour levels (when neither |
binwidth |
Spacing between contour levels, or |
breaks |
Explicit contour levels, or |
n |
Number of grid points per axis. |
h |
Bandwidth (the standard deviation of the kernel) per axis: a
number or a pair; |
adjust |
Multiplier(s) for the bandwidth, a number or a pair (default
|
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
The modified PlotSpec.
mark_contour() to contour a supplied z surface.
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)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)
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.
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 )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 )
plot |
A PlotSpec. |
... |
Encodings. |
position |
Position adjustment; see |
blend, sketch, data
|
Standard layer arguments (see |
sides |
Which edges |
length |
Rug tick length as a fraction of the panel (default |
distribution |
Quantile function of the reference distribution for
|
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
type |
Ellipse type: |
level |
Confidence level ( |
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
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
expand |
For |
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.
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings mapping node/edge attributes to aesthetics. Nodes: |
position |
Position adjustment; see |
linewidth |
For |
linetype |
For |
arrow |
For |
routing |
For |
elbow_at, elbow_axis
|
For |
gradient |
For |
auto |
For |
blend |
Optional blend mode (see |
effects |
A list of layer render effects ( |
sketch |
A |
data |
Optional layer data; overrides the default table. |
type |
For |
params |
For |
root |
For |
weight |
For |
width_range |
For |
size, shape
|
For |
fill, color, alpha
|
Convenience aesthetics; a constant or a mapped
expression. For nodes, |
label |
For |
dist |
For |
top_n, by
|
For |
repel |
For |
box_padding, point_padding, min_segment_length, seed
|
Repel
tuning for |
angle |
For |
expand |
For |
cols |
For |
inner |
For |
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.
The modified PlotSpec.
vgraph(), scale_edge_width(), scale_edge_color()
## Not run: g <- igraph::make_graph("Zachary") vgraph(g) |> mark_edges(alpha = 0.5) |> mark_nodes(size = 4, fill = "steelblue") ## End(Not run)## Not run: g <- igraph::make_graph("Zachary") vgraph(g) |> mark_edges(alpha = 0.5) |> mark_nodes(size = 4, fill = "steelblue") ## End(Not run)
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).
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 )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 )
plot |
|
... |
Encodings (tidy-eval): a categorical |
position |
Position adjustment: a string — |
.width |
Interval probabilities, widest last (default
|
point |
Central summary: |
adjust |
|
scale |
Slab width as a fraction of the category band ( |
orientation |
|
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
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).
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval), e.g. |
bins |
Number of histogram bins (default 30), used when neither
|
binwidth |
Width of each bin, overriding |
breaks |
A numeric vector of bin edges, overriding |
boundary, center
|
Where the bins are aligned: |
closed |
Which side of each bin is closed: |
position |
Position adjustment for the histogram bars ( |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
method |
Smoothing method: one of |
formula |
Model formula in terms of |
span |
|
se |
Draw a confidence ribbon around the smooth? Ignored for |
level |
Confidence level for the ribbon. |
method.args |
Extra arguments to the fitting function, e.g.
|
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.
The modified PlotSpec.
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)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)
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.
mark_image( plot, ..., position = "identity", src = NULL, size = 5, nudge_x = 0, nudge_y = 0, interpolate = TRUE, blend = NULL, data = NULL )mark_image( plot, ..., position = "identity", src = NULL, size = 5, nudge_x = 0, nudge_y = 0, interpolate = TRUE, blend = NULL, data = NULL )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
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 |
nudge_x, nudge_y
|
Shift each image by an exact absolute distance in
millimetres along the data x / y axis ( |
interpolate |
Smoothly interpolate when scaling (default |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
data |
Optional layer data frame; overrides the plot data for this layer. |
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.
The modified PlotSpec.
## 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)## 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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
method |
Outlier rule: |
k |
Threshold multiplier — IQR whisker length (default |
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
|
data |
Optional layer data frame; overrides the plot data for this layer. |
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.
The modified PlotSpec.
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> mark_outlier_label(x = wt, y = mpg, label = rownames(mtcars))vplot(mtcars) |> mark_point(x = wt, y = mpg) |> mark_outlier_label(x = wt, y = mpg, label = rownames(mtcars))
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.
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 )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 )
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. |
blend |
Optional blend mode for compositing the layer (see |
sketch |
A |
data |
Optional per-layer data frame. |
inner_radius |
For |
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings: named channel expressions such as |
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
( |
position |
Position adjustment: a string — |
auto |
For |
seed |
For |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
effects |
A list of layer render effects applied to the mark at draw
time — |
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
window |
For |
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.
The modified PlotSpec.
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.
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")).
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)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)
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()).
mark_polygon( plot, ..., position = "identity", blend = NULL, sketch = NULL, data = NULL ) mark_path( plot, ..., position = "identity", blend = NULL, effects = list(), sketch = NULL, data = NULL )mark_polygon( plot, ..., position = "identity", blend = NULL, sketch = NULL, data = NULL ) mark_path( plot, ..., position = "identity", blend = NULL, effects = list(), sketch = NULL, data = NULL )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
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 — |
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.
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
quantiles |
The conditional quantiles to fit (default
|
formula |
The model formula in |
method.args |
A list of further arguments to |
position |
Position adjustment: a string — |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
effects |
A list of layer render effects applied to the mark at draw
time — |
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
The modified PlotSpec.
mark_smooth() with method = "rq" for one quantile with the
smoother's options.
if (requireNamespace("quantreg", quietly = TRUE)) { vplot(mtcars) |> mark_point(x = disp, y = mpg) |> mark_quantile(x = disp, y = mpg) }if (requireNamespace("quantreg", quietly = TRUE)) { vplot(mtcars) |> mark_point(x = disp, y = mpg) |> mark_quantile(x = disp, y = mpg) }
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.
mark_raincloud(plot, x, y, ..., width = 0.4, alpha = 0.5)mark_raincloud(plot, x, y, ..., width = 0.4, alpha = 0.5)
plot |
A PlotSpec. |
x, y
|
The categorical |
... |
Further shared encodings (e.g. |
width |
Sina spread of the rain, as a fraction of the band (default
|
alpha |
Point opacity for the rain (default |
The modified PlotSpec.
mark_halfeye(), position_sina()
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)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)
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.
mark_rect( plot, ..., position = "identity", blend = NULL, sketch = NULL, data = NULL )mark_rect( plot, ..., position = "identity", blend = NULL, sketch = NULL, data = NULL )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
auto |
For |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
effects |
A list of layer render effects applied to the mark at draw
time — |
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
curvature |
For |
angle |
For |
ncp |
For |
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.
The modified PlotSpec.
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)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)
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.
mark_series_label( plot, ..., position = "identity", size = NULL, nudge_x = 2, repel = TRUE, box_padding = 1, min_segment_length = 2, blend = NULL, data = NULL )mark_series_label( plot, ..., position = "identity", size = NULL, nudge_x = 2, repel = TRUE, box_padding = 1, min_segment_length = 2, blend = NULL, data = NULL )
plot |
|
... |
Encodings (tidy-eval): the same |
position |
Position adjustment: a string — |
size |
Font size in points. |
nudge_x |
Rightward offset (mm) so a label clears its line end (default
|
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
|
data |
Optional layer data frame; overrides the plot data for this layer. |
The modified PlotSpec.
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")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")
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.
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 )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 )
plot |
|
... |
Encodings mapping feature attributes to aesthetics: |
position |
Position adjustment; see |
fill, color, alpha, linewidth, size
|
Convenience aesthetic arguments; a constant or a mapped expression. |
na_value |
Fill colour for features whose mapped |
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 |
blend |
Optional blend mode (see |
sketch |
A |
data |
Optional layer data (an |
sf is an optional dependency (in Suggests); mark_sf() errors with an
install hint if it is not available.
The modified PlotSpec.
coord_sf(), scale_fill_binned()
## 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)## 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)
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.
mark_sf_label( plot, ..., position = "identity", size = NULL, repel = TRUE, box_padding = 1, min_segment_length = 2, blend = NULL, data = NULL )mark_sf_label( plot, ..., position = "identity", size = NULL, repel = TRUE, box_padding = 1, min_segment_length = 2, blend = NULL, data = NULL )
plot |
|
... |
Encodings (tidy-eval): the |
position |
Position adjustment: a string — |
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
|
data |
An |
The modified PlotSpec.
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) }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) }
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): a categorical |
position |
Position adjustment: a string — |
comparisons |
A list of length-2 character vectors naming the group
pairs to test, e.g. |
method |
The two-sample test: |
label |
|
step |
Vertical gap between stacked brackets, as a fraction of the data's
y range (default |
tip_length |
Bracket down-tick length, as a fraction of the y range
(default |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
The modified PlotSpec.
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")))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")))
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.
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
size |
Font size in points. |
family, fontface
|
Font family / face ( |
hjust, vjust
|
Horizontal / vertical justification (constant; |
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 ( |
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 — |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
data |
Optional layer data frame; overrides the plot data for this layer. |
fill |
For |
sketch |
A |
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).
The modified PlotSpec.
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)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)
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.
mark_text_path( plot, ..., position = "identity", size = NULL, family = NULL, fontface = NULL, hjust = "centre", vjust = "centre", offset = 0, blend = NULL, data = NULL )mark_text_path( plot, ..., position = "identity", size = NULL, family = NULL, fontface = NULL, hjust = "centre", vjust = "centre", offset = 0, blend = NULL, data = NULL )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
size |
Font size in points. |
family, fontface
|
Font family and face ( |
hjust |
Where the run sits along the path: |
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
|
data |
Optional layer data frame; overrides the plot data for this layer. |
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.
The modified PlotSpec.
# 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)# 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)
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.)
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 )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 )
plot |
|
... |
Encodings (tidy-eval): |
position |
Position adjustment: a string — |
blend |
Optional blend mode for compositing this layer against what is
already drawn beneath it (the panel and earlier layers), one of the CSS
|
sketch |
A |
data |
Optional layer data frame; overrides the plot data for this layer. |
bins |
Number of bins per axis for |
adjust |
Bandwidth multiplier for |
trim |
For |
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.
The modified PlotSpec.
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)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)
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.
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 )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 )
plot |
A PlotSpec. |
... |
Encodings. |
position |
Position adjustment; see |
adjust |
Kernel-density bandwidth multiplier (violin/ridgeline). |
trim |
For |
orientation |
For |
blend, sketch, data
|
Standard layer arguments (see |
height |
Ridge height as a multiple of the row band (ridgeline; default
|
binwidth |
Dot-plot bin width, or |
The modified PlotSpec.
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)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)
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.
mcp_serve(input = "stdin", output = stdout())mcp_serve(input = "stdin", output = stdout())
input, output
|
Connections to read requests from / write responses to (defaults: standard input / output). |
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").
Invisibly NULL, when the input stream closes.
spec_schema(), spec_fields(), vplot_from_spec()
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.
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.
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> labs(title = md("**Fuel** economy"), y = md("Efficiency (mi gal^-1^)"))vplot(mtcars) |> mark_point(x = wt, y = mpg) |> labs(title = md("**Fuel** economy"), y = md("Efficiency (mi gal^-1^)"))
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().
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 )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 )
x, y
|
Trail direction and length in millimetres ( |
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; |
spread |
Optional widening, in millimetres, applied progressively toward
the tail ( |
blend |
Blend mode compositing the trail copies (any CSS
|
color |
Trail colour, or |
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).
A MotionSpec object for a mark's effects list.
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)))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)))
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().
outline(size = 1, color = NULL, alpha = 1)outline(size = 1, color = NULL, alpha = 1)
size |
Halo width per side, in millimetres. |
color |
Outline colour. |
alpha |
Outline opacity. |
An OutlineSpec object for a mark's effects list.
vplot(mtcars) |> mark_point(x = wt, y = mpg, color = factor(cyl), size = 3, effects = list(outline()))vplot(mtcars) |> mark_point(x = wt, y = mpg, color = factor(cyl), size = 3, effects = list(outline()))
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 = ).
pattern_hatch( color = "grey20", bg = NA, angle = 45, spacing = 3, linewidth = 0.75 )pattern_hatch( color = "grey20", bg = NA, angle = 45, spacing = 3, linewidth = 0.75 )
color |
Line colour (any R colour). Default |
bg |
Background fill painted behind the lines, or |
angle |
Line orientation in degrees. Any angle is allowed (unlike the
tile patterns, vector hatch has no seamless-tiling restriction). Default
|
spacing |
Distance between lines, in millimetres. Default |
linewidth |
Line width. Default |
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.
A vellum_hatch object, usable as a fill value.
patterns, scale_pattern(), plot_lint(), vellum::vl_hatch()
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))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))
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:
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")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")
color |
Line/dot colour (any R colour). Default |
bg |
Background fill painted behind the motif, or |
angle |
Stripe orientation in degrees, restricted to |
spacing |
Distance between repeats, in |
linewidth |
Stripe / grid line width (as elsewhere in the package).
Default |
units |
Length unit for |
size |
For |
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.
A vellum_pattern object, usable as a fill value.
linear_gradient(), vellum::vl_pattern()
df <- data.frame(g = c("a", "b", "c"), n = c(3, 5, 2)) vplot(df) |> mark_bar(x = g, y = n, fill = pattern_crosshatch())df <- data.frame(g = c("a", "b", "c"), n = c(3, 5, 2)) vplot(df) |> mark_bar(x = g, y = n, fill = pattern_crosshatch())
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.
pdf_pages(x, path)pdf_pages(x, path)
x |
Either a list of plots (each a PlotSpec, composition, or table)
— one page each — or a single faceted |
path |
Output |
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.
path, invisibly.
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"))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"))
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.
plot_alt(x)plot_alt(x)
x |
A PlotSpec or a plot composition. |
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.
A single string.
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."))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."))
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.
plot_data_uri( plot, format = c("svg", "png"), width = NULL, height = NULL, dpi = NULL, ... )plot_data_uri( plot, format = c("svg", "png"), width = NULL, height = NULL, dpi = NULL, ... )
plot |
A PlotSpec (or any object |
format |
|
width, height
|
Optional size override in inches. |
dpi |
For |
... |
Passed to |
A length-1 character data: URI.
uri <- vplot(mtcars) |> mark_point(x = wt, y = mpg) |> plot_data_uri() substr(uri, 1, 30)uri <- vplot(mtcars) |> mark_point(x = wt, y = mpg) |> plot_data_uri() substr(uri, 1, 30)
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.
plot_lint(x, ..., min_text_px = 7, min_contrast = 3)plot_lint(x, ..., min_text_px = 7, min_contrast = 3)
x |
A PlotSpec (or anything |
... |
Passed to |
min_text_px |
Minimum legible text height in pixels (default |
min_contrast |
Minimum acceptable contrast ratio between a mark and its
background (default |
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).
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.
render_plot() (cvd =), scale_pattern(), pattern_hatch(),
vellum::vl_lint(), vellum::vl_lint_overlay(), vellum::vl_lint_assert()
# 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 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")
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.
plot_manifest(x)plot_manifest(x)
x |
A PlotSpec. |
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.
plot_verify(), plot_svg(), provenance_join()
plot_manifest(vplot(mtcars) |> mark_point(x = wt, y = mpg))$data$hashplot_manifest(vplot(mtcars) |> mark_point(x = wt, y = mpg))$data$hash
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.
plot_provenance(x)plot_provenance(x)
x |
A PlotSpec or plot composition. |
Each record is a plain, serializable list:
idstable node id, equal to grob@id / SVG data-vellum-id (join key).
layer1-based layer index within the (sub-)plot spec.
markmark type ("point", "line", …).
kind"mark" (the core layer) or "effect" (a decorative underlay).
panelfacet panel key ("panel-r-c"), or NA for a single panel.
channelsaesthetic → trained-scale reference (scale, type, domain).
rowsthe original input-data row indices this grob draws: rows of the whole source table (not of a facet panel's subset).
sourcethe 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.
A list of provenance records (see Details). Empty for a plot that emits no mark grobs.
vellum::scene_model() and the scene-contract vignette in vellum.
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]]$iddf <- 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
Use inside concat() / wrap_plots() (or a design) to leave a gap.
plot_spacer()plot_spacer()
A spacer placeholder.
a <- vplot(mtcars) |> mark_point(x = wt, y = mpg) concat(a, plot_spacer(), a, plot_spacer(), ncol = 2)a <- vplot(mtcars) |> mark_point(x = wt, y = mpg) concat(a, plot_spacer(), a, plot_spacer(), ncol = 2)
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.
plot_svg( plot, width = NULL, height = NULL, scaling = c("fixed", "fit"), inline = FALSE, recolor = NULL, text = "native", manifest = FALSE )plot_svg( plot, width = NULL, height = NULL, scaling = c("fixed", "fit"), inline = FALSE, recolor = NULL, text = "native", manifest = FALSE )
plot |
|
width, height
|
Optional page-size override in inches (defaults to the object's own size). |
scaling |
|
inline |
|
recolor |
Optional named character vector mapping a source colour to a
replacement written verbatim into the SVG — e.g.
|
text |
How glyphs are emitted: |
manifest |
If |
A length-1 character SVG string.
vsparkline(), gt_vsparkline(), render_plot(), plot_manifest()
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") )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") )
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.
plot_verify(svg, data)plot_verify(svg, data)
svg |
An SVG string (from |
data |
The data frame to check the figure against. |
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.
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.
svg <- plot_svg(vplot(mtcars) |> mark_point(x = wt, y = mpg), manifest = TRUE) plot_verify(svg, mtcars)$oksvg <- plot_svg(vplot(mtcars) |> mark_point(x = wt, y = mpg), manifest = TRUE) plot_verify(svg, mtcars)$ok
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().
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 )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 )
data |
The data frame. |
edge_data |
For a graph plot (from |
layers |
A list of layer specifications (one per |
scales |
A list of declared scale overrides. |
facet |
A faceting specification (from |
coord |
A coordinate specification (from |
resolve |
A named list mapping an aesthetic to |
width, height
|
Page size in inches. |
dpi |
Output resolution in dots per inch (pixels per inch). The exported
PNG's pixel dimensions are |
theme |
A theme (a named list of resolved element/setting overrides, from
|
labels |
A named list of plot/axis/legend label overrides (see |
marginal |
A marginal-distribution specification (from |
selections |
A list of interactive selection declarations (from
|
filters |
A list of filter declarations (from |
binds |
A list of scale-domain bind declarations (from |
clip |
A |
transition |
A keyframe-animation transition (from |
ease |
An animation easing (from |
source |
A source-inspection declaration (from |
A PlotSpec.
vplot(), mark_point(), scale_x_continuous()
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.
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 )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 )
x, y
|
|
width, height
|
Maximum jitter (data units); |
seed |
Optional integer seed for the random jitter. |
preserve |
|
padding |
|
vjust |
|
dodge.width, jitter.width, jitter.height
|
|
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).
A vellumplot_position object for a mark's position argument.
vplot(mtcars) |> mark_point(x = factor(cyl), y = mpg, position = position_jitter(width = 0.15))vplot(mtcars) |> mark_point(x = factor(cyl), y = mpg, position = position_jitter(width = 0.15))
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.
provenance_join(x)provenance_join(x)
x |
A PlotSpec or composition. |
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.
plot_provenance(), vellum::scene_model()
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")]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")]
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.
provenance_payload(x, values = FALSE)provenance_payload(x, values = FALSE)
x |
A PlotSpec or composition. |
values |
If |
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.
A list with
fieldsthe plot data's column names.
elementsa list of list(id, rows, source) records.
sourcesfor 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.
datawhen values = TRUE, row-wise records of the plot's data
(the "plot" source, kept at the top level for existing hosts).
provenance_join(), plot_provenance()
p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = factor(cyl)) pl <- provenance_payload(p) pl$elements[[1]]$id pl$elements[[1]]$sourcep <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = factor(cyl)) pl <- provenance_payload(p) pl$elements[[1]]$id pl$elements[[1]]$source
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.
rel(x)rel(x)
x |
A single positive number, the multiplier. |
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.
A number of class rel, for the size of element_text().
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> theme(axis.text = element_text(size = rel(1.2)))vplot(mtcars) |> mark_point(x = wt, y = mpg) |> theme(axis.text = element_text(size = rel(1.2)))
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.
render_all(plots, paths, workers = NULL, ...)render_all(plots, paths, workers = NULL, ...)
plots |
A named or unnamed list of plots. |
paths |
Output paths, one per plot (the format of each comes from its
extension, as in |
workers |
Number of parallel workers; |
... |
Passed to each |
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.
paths (the resolved file paths), invisibly.
render_plot(), pdf_pages(), repeat_()
plots <- list( wt = vplot(mtcars) |> mark_point(x = wt, y = mpg), hp = vplot(mtcars) |> mark_point(x = hp, y = mpg) ) render_all(plots, tempdir())plots <- list( wt = vplot(mtcars) |> mark_point(x = wt, y = mpg), hp = vplot(mtcars) |> mark_point(x = hp, y = mpg) ) render_all(plots, tempdir())
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.
render_plot(plot, path, text = "native", dpi = NULL, cvd = "none")render_plot(plot, path, text = "native", dpi = NULL, cvd = "none")
plot |
A PlotSpec. |
path |
Output file path. |
text |
For SVG output, how text is written (see |
dpi |
Output resolution in dots per inch. |
cvd |
Colour-vision-deficiency simulation for a |
path, invisibly.
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 blindnessp <- 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
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.
repeat_(plot, ..., ncol = NULL, nrow = NULL)repeat_(plot, ..., ncol = NULL, nrow = NULL)
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 |
... |
Named aesthetics, each a character vector of field names, e.g.
|
ncol, nrow
|
Grid dimensions (passed to |
A PlotComposition.
repeat_(vplot(mtcars) |> mark_point(y = mpg), x = c("wt", "hp", "disp"))repeat_(vplot(mtcars) |> mark_point(y = mpg), x = c("wt", "hp", "disp"))
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".
resolve_scale(plot, ...)resolve_scale(plot, ...)
plot |
A PlotSpec. |
... |
Named arguments mapping an aesthetic ( |
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.
The modified PlotSpec.
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"))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"))
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.
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 )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 )
plot |
A PlotSpec. |
range |
Numeric length-2 output opacity range, or |
limits |
Numeric length-2 data domain, or |
breaks |
Explicit legend breaks, or |
name |
Legend title, or |
oob |
What to do with values outside |
values |
For |
labels |
For the discrete forms, legend labels (one per key, a vector
named by level, or a function), or |
na.value |
For the discrete forms, the opacity drawn for missing
values, or |
drop |
For the discrete forms, drop factor levels that no row uses
(default |
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).
The modified PlotSpec.
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))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))
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.
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 )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 )
plot |
A PlotSpec. |
palette |
A vector of colours, or a single palette name passed to
|
limits |
For the continuous colour scales (including the gradient
ones), a length-2 numeric |
breaks, labels
|
Explicit legend breaks / labels, or |
name |
Legend title, or |
oob |
For the continuous scales ( |
drop |
For the discrete scales, drop factor levels that no row uses
(default |
values |
For |
na.value |
For the gradient scales, the colour of missing (and
censored) values; for |
low, high
|
For |
mid |
For |
midpoint |
For |
colours |
For |
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.
The modified PlotSpec.
vplot(mtcars) |> mark_point(x = wt, y = mpg, color = hp) |> scale_color_continuous(palette = "Batlow")vplot(mtcars) |> mark_point(x = wt, y = mpg, color = hp) |> scale_color_continuous(palette = "Batlow")
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.
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)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)
plot |
A PlotSpec. |
The modified PlotSpec.
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()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()
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.
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)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)
plot |
|
palette |
For |
name |
Legend title, or |
midpoint |
For |
range |
For |
limits, breaks, labels
|
Data limits, explicit legend breaks, and explicit
labels, or |
values |
For |
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.
The modified PlotSpec.
mark_edges(), scale_edge_width(), vgraph()
## 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)## 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)
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.
scale_edge_width(plot, range = NULL, limits = NULL, breaks = NULL, name = NULL)scale_edge_width(plot, range = NULL, limits = NULL, breaks = NULL, name = NULL)
plot |
A PlotSpec. |
range |
Output line-width range |
limits |
Data limits |
breaks |
Explicit legend breaks, or |
name |
Legend title, or |
The modified PlotSpec.
## 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)## 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)
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.
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 )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 )
plot |
A PlotSpec. |
style |
Classification style: |
n |
For |
breaks |
Explicit class boundaries, overriding |
palette |
A sequential palette: |
labels |
Optional class labels (one per class); defaults to interval
ranges like |
na_value |
Fill colour for |
name |
Legend title, or |
low, mid, high, midpoint
|
For |
limits |
For the ggplot2-named scales, a length-2 numeric
|
n.breaks |
For the ggplot2-named scales, the approximate number of
class boundaries when |
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: |
colours |
For |
values |
For |
type, direction
|
For |
option |
For |
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.
The modified PlotSpec.
mark_sf(), scale_fill_continuous()
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()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()
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.
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" )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" )
plot |
A PlotSpec. |
palette |
A palette name for |
dim |
Classes per variable ( |
xlab, ylab
|
The legend's axis titles. |
name |
A title above the legend grid. |
na_value |
Fill for features with a missing class. Default |
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.
The modified PlotSpec.
bi_class(), guide_bivariate(), bi_pal()
Other bivariate:
bi_class(),
bi_pal(),
guide_bivariate()
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") }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") }
ggplot2's other discrete colour scales, for code migrating from it.
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 )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 )
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 |
|
name |
Legend title, or |
breaks, labels
|
The levels the legend shows and their labels (one per
shown level, a vector named by level, or a function), or |
limits |
The levels the scale covers, or |
na.value |
Colour for missing values (and levels outside |
drop |
For the discrete scales, drop factor levels that no row uses
(default |
start, end
|
Grey levels of the first and last colour, in |
option |
For |
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.
The modified PlotSpec.
scale_color_discrete(), scale_viridis
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()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()
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()).
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 )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 )
plot |
A PlotSpec. |
values |
Character vector of line types (each one of |
name |
Legend title, or |
breaks, labels, limits
|
As for |
na.value |
The line type drawn for missing values, or |
drop |
For the discrete scales, drop factor levels that no row uses
(default |
The modified PlotSpec.
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"))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"))
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.
scale_linewidth(plot, range = NULL, limits = NULL, breaks = NULL, name = NULL) scale_linewidth_continuous( plot, range = NULL, limits = NULL, breaks = NULL, name = NULL )scale_linewidth(plot, range = NULL, limits = NULL, breaks = NULL, name = NULL) scale_linewidth_continuous( plot, range = NULL, limits = NULL, breaks = NULL, name = NULL )
plot |
A PlotSpec. |
range |
Output line-width range |
limits |
Data limits |
breaks |
Explicit legend breaks, or |
name |
Legend title, or |
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.)
The modified PlotSpec.
mark_line(), mark_step(), mark_segment(), scale_edge_width()
vplot(pressure) |> mark_line(x = temperature, y = pressure, linewidth = pressure) |> scale_linewidth(range = c(0.5, 5))vplot(pressure) |> mark_line(x = temperature, y = pressure, linewidth = pressure) |> scale_linewidth(range = c(0.5, 5))
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).
scale_pattern(plot, values = NULL, name = NULL)scale_pattern(plot, values = NULL, name = NULL)
plot |
A PlotSpec. |
values |
Optional textures, one per level: a character vector of builder
names ( |
name |
Optional legend title. |
The modified PlotSpec.
pattern_stripe(), scale_shape()
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()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()
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.
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 )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 )
plot |
A PlotSpec. |
values |
Character vector of shapes, or For |
name |
Legend title, or |
breaks |
The levels the legend shows (and their order), or |
labels |
Legend labels: one per shown level, a vector named by level,
or a function of the levels; |
limits |
The levels the scale covers (a character vector), or |
na.value |
The shape drawn for missing values (default a circle). |
drop |
For the discrete scales, drop factor levels that no row uses
(default |
The modified PlotSpec.
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))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))
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.
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 )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 )
plot |
A PlotSpec. |
range |
Numeric length-2 output size range in mm, or |
limits |
Numeric length-2 data domain, or |
breaks |
Explicit legend breaks, or |
name |
Legend title, or |
oob |
What to do with values outside |
max_size |
For |
labels |
For |
n.breaks |
For |
values |
For |
na.value |
For the discrete forms, the size drawn for missing values,
or |
drop |
For the discrete forms, drop factor levels that no row uses
(default |
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.
The modified PlotSpec.
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))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))
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).
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 )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 )
plot |
A PlotSpec. |
option |
Which viridis map (see above). |
name, breaks, labels
|
As for |
limits, oob, na.value
|
For the continuous scales ( |
drop |
For the discrete scales, drop factor levels that no row uses
(default |
palette |
A ColorBrewer palette name or index (see above), or a
|
type |
When |
direction |
|
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().
The modified PlotSpec.
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")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")
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.
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 )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 )
plot |
A PlotSpec. |
style |
Binning style: |
n |
Target number of bins. |
breaks |
Explicit bin boundaries (overrides |
labels |
Explicit boundary labels, or |
name |
Axis title, or |
guide |
The axis guide: |
The modified PlotSpec.
vplot(mtcars) |> mark_point(x = wt, y = mpg) |> scale_x_binned(n = 6)vplot(mtcars) |> mark_point(x = wt, y = mpg) |> scale_x_binned(n = 6)
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().
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 )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 )
plot |
A PlotSpec. |
limits |
For continuous scales a numeric length-2 domain |
trans |
Transformation: |
breaks, labels
|
Explicit break positions (data units) and their labels,
or |
name |
Axis title, or |
expand |
Axis padding beyond the data. |
sec.axis |
A secondary axis from |
oob |
What to do with values outside |
guide |
The axis guide: |
... |
For the transform shortcuts, further arguments to
|
drop |
For discrete scales, drop factor levels that do not occur in
the data (default |
The modified PlotSpec.
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")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")
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.
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 )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 )
plot |
A PlotSpec. |
limits |
Length-2 vector giving the axis range (same class as the data),
or |
date_breaks |
A break interval string, e.g. |
date_labels |
A |
breaks, labels
|
Explicit break positions / labels (override
|
name |
Axis title, or |
guide |
The axis guide: |
The modified PlotSpec.
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")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")
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.
sec_axis(transform = ~., name = NULL, breaks = NULL, labels = NULL) dup_axis(transform = ~., name = NULL, breaks = NULL, labels = NULL)sec_axis(transform = ~., name = NULL, breaks = NULL, labels = NULL) dup_axis(transform = ~., name = NULL, breaks = NULL, labels = NULL)
transform |
The primary-to-secondary mapping: a formula using |
name |
Secondary axis title, or |
breaks |
Break positions in secondary units, or |
labels |
A character vector of labels (one per break) or a labelling
function, or |
sec_axis() maps the primary axis through transform; dup_axis() is the
identity special case (a plain duplicate) with tidy defaults.
A SecAxisSpec to pass to sec.axis.
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.
# 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())# 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())
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.
select_interval( plot, name, encodings = c("x", "y"), region = c("rect", "lasso"), empty = TRUE, on = NULL, bind = NULL )select_interval( plot, name, encodings = c("x", "y"), region = c("rect", "lasso"), empty = TRUE, on = NULL, bind = NULL )
plot |
A PlotSpec (piped form), or a selection name string (free-standing form). |
name |
The selection name (piped form), referenced by |
encodings |
The position channels the brush constrains: |
region |
|
empty |
Whether an empty selection contains all elements ( |
on |
Deprecated alias for |
bind |
|
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()).
A PlotSpec (piped form) or a SelectionSpec (free-standing form).
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.
select_point(), condition(), filter_by(), add_selection(),
bind_scale()
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) )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) )
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.
select_neighbours( plot, name = "neighbours", on = c("hover", "click"), degree = 1L, edges = TRUE, empty = TRUE )select_neighbours( plot, name = "neighbours", on = c("hover", "click"), degree = 1L, edges = TRUE, empty = TRUE )
plot |
A PlotSpec, normally from |
name |
The selection name. Defaults to |
on |
The gesture: |
degree |
How many hops out from the pointed node to include ( |
edges |
Whether to include the incident edges in the highlight
( |
empty |
Whether an empty selection matches all elements ( |
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.
A PlotSpec (piped form) or a SelectionSpec (free-standing form).
select_point(), condition(), vgraph(), mark_edges()
## Not run: g <- igraph::make_graph("Zachary") vgraph(g) |> mark_edges() |> mark_nodes(size = 3) |> select_neighbours(on = "hover") ## End(Not run)## Not run: g <- igraph::make_graph("Zachary") vgraph(g) |> mark_edges() |> mark_nodes(size = 3) |> select_neighbours(on = "hover") ## End(Not run)
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.
select_point( plot, name, on = c("click", "hover"), fields = NULL, group_by = NULL, toggle = TRUE, empty = TRUE )select_point( plot, name, on = c("click", "hover"), fields = NULL, group_by = NULL, toggle = TRUE, empty = TRUE )
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: |
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. |
group_by |
Alias for |
toggle |
For a point selection, whether clicking toggles membership
( |
empty |
Whether an empty selection contains all elements ( |
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()).
A PlotSpec (piped form) or a SelectionSpec (free-standing form).
select_interval(), condition(), filter_by(),
add_selection(), bind_scale()
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")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")
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().
shadow( x = 0.5, y = -0.5, color = "black", alpha = 0.3, spread = 1.5, layers = 3L )shadow( x = 0.5, y = -0.5, color = "black", alpha = 0.3, spread = 1.5, layers = 3L )
x, y
|
Shadow offset in millimetres ( |
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). |
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).
A ShadowSpec object for a mark's effects list.
df <- data.frame(x = 1:20, y = cumsum(rnorm(20))) vplot(df) |> mark_line(x = x, y = y, effects = list(shadow()))df <- data.frame(x = 1:20, y = cumsum(rnorm(20))) vplot(df) |> mark_line(x = x, y = y, effects = list(shadow()))
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():
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.
theme_sketch(), mark_point(), element_line()
vplot(mtcars) |> mark_point(x = wt, y = mpg, sketch = sketch(roughness = 1.5, seed = 7))vplot(mtcars) |> mark_point(x = wt, y = mpg, sketch = sketch(roughness = 1.5, seed = 7))
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.
spec_diagnose(spec, data = NULL, env = globalenv()) vplot_from_spec(spec, data = NULL, env = globalenv())spec_diagnose(spec, data = NULL, env = globalenv()) vplot_from_spec(spec, data = NULL, env = globalenv())
spec |
A spec list (from |
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. |
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.
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.
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).
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.
spec_fields(), spec_schema(), vplot_ask()
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)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)
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.
spec_fields(data, n_examples = 3L)spec_fields(data, n_examples = 3L)
data |
A data frame. |
n_examples |
How many example values to show per field (default 3). |
A data frame with columns name, type, class, n_unique,
examples.
vplot_from_spec(), spec_schema()
spec_fields(mtcars)spec_fields(mtcars)
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.
spec_schema(as = c("string", "list", "path"))spec_schema(as = c("string", "list", "path"))
as |
A character scalar: |
The schema as a string, a list, or a file path.
schema <- spec_schema(as = "list") schema$titleschema <- spec_schema(as = "list") schema$title
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.
spec_to_json(plot, pretty = TRUE) spec_from_json(json, data = NULL, env = globalenv())spec_to_json(plot, pretty = TRUE) spec_from_json(json, data = NULL, env = globalenv())
plot |
A PlotSpec. |
pretty |
Whether to pretty-print (default |
json |
A JSON spec string (or a path to a |
data, env
|
Passed to |
spec_to_json() returns a length-1 JSON string; spec_from_json()
returns a PlotSpec.
as_spec(), spec_schema(), vplot_from_spec()
p <- vplot(mtcars) |> mark_point(x = wt, y = mpg) json <- spec_to_json(p) p2 <- spec_from_json(json)p <- vplot(mtcars) |> mark_point(x = wt, y = mpg) json <- spec_to_json(p) p2 <- spec_from_json(json)
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.
spec_to_vegalite(plot, json = FALSE) spec_from_vegalite(vl, data = NULL, env = globalenv())spec_to_vegalite(plot, json = FALSE) spec_from_vegalite(vl, data = NULL, env = globalenv())
plot |
A PlotSpec. |
json |
For |
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
|
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.
spec_to_vegalite() returns a Vega-Lite spec (a list, or JSON string
if json = TRUE); spec_from_vegalite() returns a PlotSpec.
p <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = cyl) vl <- spec_to_vegalite(p) vl$markp <- vplot(mtcars) |> mark_point(x = wt, y = mpg, color = cyl) vl <- spec_to_vegalite(p) vl$mark
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).
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 )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 )
plot |
A PlotSpec. |
base_size |
Base text size in points (default 11). Every text element
is sized relative to it, so |
base_family |
Base font family for all text; |
... |
Named theme elements, e.g. |
panel_bg, grid_col, label_col, strip_bg
|
Colours (or |
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.
The modified PlotSpec.
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))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))
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.
theme_sketch( plot, roughness = 1, bowing = 1, fill_style = "hachure", seed = 1L, font = NULL, paper = "#f4ecd8", ink = "#2b2b2b" )theme_sketch( plot, roughness = 1, bowing = 1, fill_style = "hachure", seed = 1L, font = NULL, paper = "#f4ecd8", ink = "#2b2b2b" )
plot |
A PlotSpec. |
roughness, bowing, fill_style, seed
|
Passed to |
font |
Font family for all text (text is not sketched; a handwriting font
such as |
paper, ink
|
Background and foreground (text/line) colours. Setting
either also makes them the default mark colours ( |
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.
The modified PlotSpec.
sketch(), theme_gray(), mark_point()
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)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)
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.
transition_reveal(plot, along)transition_reveal(plot, along)
plot |
|
along |
The variable the reveal follows: numeric, |
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).
The modified PlotSpec.
transition_states(), transition_time(), animate()
vplot(data.frame(t = 1:20, y = cumsum(rnorm(20)))) |> mark_line(x = t, y = y) |> transition_reveal(t)vplot(data.frame(t = 1:20, y = cumsum(rnorm(20)))) |> mark_line(x = t, y = y) |> transition_reveal(t)
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).
transition_states( plot, states, transition_length = 1, state_length = 1, wrap = TRUE )transition_states( plot, states, transition_length = 1, state_length = 1, wrap = TRUE )
plot |
|
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? |
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.
The modified PlotSpec.
ease_aes(), animate(), anim_save()
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) }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) }
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.
transition_time(plot, time)transition_time(plot, time)
plot |
|
time |
A numeric, |
{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.
The modified PlotSpec.
transition_states(), ease_aes(), animate()
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) }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) }
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.
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 )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 )
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
|
sort |
Sector and ribbon order: |
link_color |
Colour ribbons by their |
direction |
How to show a ribbon's direction: |
label |
Label each sector with its node name? Default |
width, height, dpi
|
Page size (inches) and resolution. |
plot |
A PlotSpec. |
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).
A PlotSpec (vchord()) or the modified plot (mark_chord()).
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)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)
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.
vdendrogram( x, direction = c("down", "up", "left", "right"), k = NULL, labels = TRUE, label_size = 5, width = 7, height = 5, dpi = 96 )vdendrogram( x, direction = c("down", "up", "left", "right"), k = NULL, labels = TRUE, label_size = 5, width = 7, height = 5, dpi = 96 )
x |
An |
direction |
Growth direction (leaves opposite the root): |
k |
Optionally cut the tree into |
labels |
Draw the leaf labels? Default |
label_size |
Leaf-label font size (points). Default |
width, height, dpi
|
Page size (inches) and resolution. |
A PlotSpec.
vgraph() for the general node-link path (layout = "dendrogram"
or "unrooted").
hc <- hclust(dist(USArrests)) vdendrogram(hc, k = 3)hc <- hclust(dist(USArrests)) vdendrogram(hc, k = 3)
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.
vgraph( g, layout = "stress", ..., augment = FALSE, filter_nodes = NULL, filter_edges = NULL, k_core = NULL, seed = 42L, width = 6, height = 4, dpi = 96 )vgraph( g, layout = "stress", ..., augment = FALSE, filter_nodes = NULL, filter_edges = NULL, k_core = NULL, seed = 42L, width = 6, height = 4, dpi = 96 )
g |
An |
layout |
A layout: a name ( |
... |
Extra arguments forwarded to the layout function (e.g. |
augment |
Opt-in vertex metrics to attach as graph attributes (so they
can be mapped – |
filter_nodes, filter_edges
|
Data-masked predicates that keep the vertices
/ edges for which they are |
k_core |
Keep only the k-core: vertices with coreness |
seed |
Integer seed for stochastic layouts ( |
width, height
|
Page size in inches. |
dpi |
Output resolution in dots per inch (see |
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.
A PlotSpec whose data is the node table and whose edge_data is the
edge table.
mark_edges(), mark_nodes(), mark_node_text()
## 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)## 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)
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.
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 )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 )
data |
A data frame describing a hierarchy (a parent list). |
id, parent, value
|
Columns (tidy-eval): the node id, its parent id
( |
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 |
type |
Diagram geometry: |
inner_radius |
Sunburst only: central hole radius, a fraction in
|
flow |
Icicle only: the direction of increasing depth — |
lighten |
Branch mode only: how far the deepest level fades toward white,
a fraction in |
label |
Label each node with its |
show_values |
Append each node's value to its label, e.g. |
orientation |
Sunburst labels only: |
root_label |
Write the root's name (and, with |
width, height, dpi
|
Page size (inches) and resolution. |
plot |
A PlotSpec. |
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.
A PlotSpec (vhierarchy()) or the modified plot (mark_hierarchy()).
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.
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")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")
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.
pattern_stripe(), linear_gradient()
dots <- vellum::circle_grob(r = 0.25, gp = vellum::vl_gpar(fill = "grey30")) vl_pattern(dots, width = 0.08, height = 0.08)dots <- vellum::circle_grob(r = 0.25, gp = vellum::vl_gpar(fill = "grey30")) vl_pattern(dots, width = 0.08, height = 0.08)
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.
vplot(data, width = 6, height = 4, dpi = 96)vplot(data, width = 6, height = 4, dpi = 96)
data |
A data frame. Encoding expressions in |
width, height
|
Page size in inches. |
dpi |
Output resolution in dots per inch. The exported PNG's pixel
dimensions are |
A PlotSpec.
vplot(mtcars) |> mark_point(x = wt, y = mpg)vplot(mtcars) |> mark_point(x = wt, y = mpg)
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().
vplot_ask(prompt, data, responder, env = globalenv())vplot_ask(prompt, data, responder, env = globalenv())
prompt |
A natural-language description of the desired plot. |
data |
The data frame to plot. |
responder |
A function |
env |
Environment channel expressions are re-quoted in. |
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")).
A PlotSpec.
spec_fields(), vplot_from_spec(), spec_schema()
# 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)# 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)
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.
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 )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 )
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 |
show_values |
Append each node's value to its label (e.g. |
flow_color |
Ribbon fill: |
node_width |
Node-rectangle width, as a fraction of the plotting width
(default |
node_gap |
Vertical gap between the nodes in a column, as a fraction of
the column height (default |
width, height, dpi
|
Page size (inches) and resolution. |
plot |
A PlotSpec. |
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.
A PlotSpec (vsankey()) or the modified plot (mark_sankey()).
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")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")
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.
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 )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 )
values |
A numeric vector (the series), length >= 2. |
type |
|
color |
Trend / bar colour. |
points |
For |
point_color |
Dot colour. |
baseline |
For |
win_color, loss_color
|
For |
linewidth |
Trend line width (default |
point_size |
Dot diameter in mm (default |
width, height, units
|
Physical size of the sparkline; |
dpi |
Resolution for raster output. |
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.
A PlotSpec.
set.seed(1) vsparkline(cumsum(rnorm(30))) vsparkline(rpois(20, 5), type = "bar") vsparkline(sample(c(-1, 1), 20, replace = TRUE), type = "winloss")set.seed(1) vsparkline(cumsum(rnorm(30))) vsparkline(rpois(20, 5), type = "bar") vsparkline(sample(c(-1, 1), 20, replace = TRUE), type = "winloss")
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.
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 )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 )
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
|
cols |
Character vector of columns to show, in order (default all). |
align |
Optional named list of per-column alignment
( |
header |
Draw a bold header row with an underline (default |
font_size |
Text size in points (default |
spark_width |
Width of a sparkline column, in |
row_height |
Row height, in |
cell_pad |
Horizontal padding inside a text cell, in |
units |
Length unit for the sizes above: |
dpi |
Resolution for raster output. |
A VTable (renders via render_plot()).
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"))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"))
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.
vvenn(sets, width = 5, height = 5, dpi = 96)vvenn(sets, width = 5, height = 5, dpi = 96)
sets |
Either a named list of member vectors ( |
width, height, dpi
|
Figure size (inches) and resolution. |
A PlotSpec; print or render_plot() it.
vvenn(list( Coffee = c("Ann", "Bo", "Cy", "Di"), Tea = c("Bo", "Di", "Ed", "Fi") ))vvenn(list( Coffee = c("Ann", "Bo", "Cy", "Di"), Tea = c("Bo", "Di", "Ed", "Fi") ))
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.
vwaffle( data, category, value = NULL, n_cells = 100, rows = 10, flip = FALSE, pad = 0.12, width = 5, height = 5, dpi = 96 )vwaffle( data, category, value = NULL, n_cells = 100, rows = 10, flip = FALSE, pad = 0.12, width = 5, height = 5, dpi = 96 )
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 |
rows |
Number of rows in the grid (default |
flip |
Fill row by row (left to right) instead of column by column. |
pad |
Gap between cells, as a fraction of a cell (default |
width, height, dpi
|
Page size (inches) and resolution for the standalone chart. |
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.
A PlotSpec.
df <- data.frame(part = c("a", "b", "c"), n = c(50, 30, 20)) vwaffle(df, category = part, value = n)df <- data.frame(part = c("a", "b", "c"), n = c(50, 30, 20)) vwaffle(df, category = part, value = n)