| Title: | Grammar of Graphics on 'base' Graphics |
|---|---|
| Description: | Implements a grammar of graphics on top of the 'base' graphics system. A 'bbplot' object is built incrementally with a '+' operator from data, aesthetic mappings and layers, then rendered with base graphics, so plotbb layers can be mixed with ordinary base plotting calls. The package provides layers for points, lines, bars, histograms, densities, boxplots, violins, ribbons, smooths, error bars and tiles, together with colour and other aesthetic scales, automatic legends, faceting, themes, coordinate flipping and significance annotations. |
| Authors: | Guangchuang Yu [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-6485-8781>) |
| Maintainer: | Guangchuang Yu <[email protected]> |
| License: | Artistic-2.0 |
| Version: | 1.0.0 |
| Built: | 2026-10-18 14:59:38 UTC |
| Source: | https://github.com/cran/plotbb |
convert a base plot function to a bbplot object
as.bbplot(fun)as.bbplot(fun)
fun |
a function that plot something in base graphics |
the base plot function will be plotted as a canvas and users can apply theme and add layers to it
A bbplot object
Guangchuang Yu
aesthetic mapping
bb_aes(x, y, ...)bb_aes(x, y, ...)
x |
x variable |
y |
y variable |
... |
other mappings |
aesthetic mapping for bbplot
enquo expression describing variables mapping to aesthetic attributes
Guangchuang Yu
boxplot layer
density layer
histogram layer
layer
reference lines
ribbon layer
significance layer
smooth layer
violin layer
bb_bar( mapping = NULL, data = NULL, stat = "identity", width = 0.9, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_boxplot( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_density( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_errorbar( mapping = NULL, data = NULL, orientation = "y", width = 0.5, inherit = TRUE, ... ) bb_hist( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_line(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_lm( mapping = NULL, data = NULL, se = TRUE, level = 0.95, inherit = TRUE, ... ) bb_point( mapping = NULL, data = NULL, position = "identity", inherit = TRUE, ..., seed = 1 ) bb_hline( yintercept = NULL, mapping = NULL, data = NULL, inherit = TRUE, expand_limits = FALSE, ... ) bb_vline( xintercept = NULL, mapping = NULL, data = NULL, inherit = TRUE, expand_limits = FALSE, ... ) bb_ribbon( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_segment(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_signif(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_smooth( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_text(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_tile(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_violin( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... )bb_bar( mapping = NULL, data = NULL, stat = "identity", width = 0.9, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_boxplot( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_density( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_errorbar( mapping = NULL, data = NULL, orientation = "y", width = 0.5, inherit = TRUE, ... ) bb_hist( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_line(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_lm( mapping = NULL, data = NULL, se = TRUE, level = 0.95, inherit = TRUE, ... ) bb_point( mapping = NULL, data = NULL, position = "identity", inherit = TRUE, ..., seed = 1 ) bb_hline( yintercept = NULL, mapping = NULL, data = NULL, inherit = TRUE, expand_limits = FALSE, ... ) bb_vline( xintercept = NULL, mapping = NULL, data = NULL, inherit = TRUE, expand_limits = FALSE, ... ) bb_ribbon( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_segment(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_signif(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_smooth( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... ) bb_text(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_tile(mapping = NULL, data = NULL, inherit = TRUE, ...) bb_violin( mapping = NULL, data = NULL, inherit = TRUE, orientation = c("vertical", "horizontal"), ... )
mapping |
aesthetic mapping |
data |
layer data |
stat |
one of 'identity' or 'count' |
width |
bar width or errorbar cap width |
inherit |
whether the layer inherits the plot mapping. With
|
orientation |
'"vertical"' (default; 'x' groups, 'y' values) or '"horizontal"' ('x' values, 'y' groups). |
... |
additional parameters: 'width' (default 0.9), 'adjust' (1), 'bw', 'kernel', 'trim', 'n', 'alpha', 'border', 'fill'/'col'. |
se |
display confidence interval around smooth? (TRUE by default, see ggplot2) |
level |
level of confidence interval to use (0.95 by default) |
position |
one of 'identity' or 'jitter' |
seed |
random seed used by 'position = "jitter"'. Defaults to 1, so
that jittered positions are reproducible; set |
yintercept |
numeric y position(s) for horizontal lines |
expand_limits |
whether the intercept extends the axis range |
xintercept |
numeric x position(s) for vertical lines |
bbplot layers
'bb_hline()' and 'bb_vline()' draw horizontal and vertical reference lines. The position is either a constant vector ('yintercept' / 'xintercept') or a mapping of the same name, so thresholds can come from the data as well.
By default a reference line does **not** change the axis range: a line at the edge of the data should not silently extend the canvas. Set 'expand_limits = TRUE' when the intercept is meant to be inside the visible range even though the data do not reach it.
A mapped intercept wins over the constant argument. With a mapped intercept, 'col' and 'lty' may also be mapped and are then applied per line; with a constant intercept those aesthetics are layer-wide constants.
When the layer brings its own data, inherited mappings are evaluated on that data too; use 'inherit = FALSE' when the plot maps aesthetics the reference lines do not carry.
The layers follow the grammar contract: they inherit data and mapping, accept their own, draw in '+' order, honour constant 'col', 'lty' and 'lwd', and are drawn once per facet panel.
'bb_ribbon()' draws a band between 'ymin' and 'ymax' along 'x', one polygon per group. It follows the grammar contract: it inherits the plot data and mapping, accepts its own, draws in '+' order, honours constants and contributes 'x', 'ymin' and 'ymax' to the ranges.
Rows with a missing or non-finite 'x', 'ymin' or 'ymax' are dropped, and so are rows with a missing group (with a warning). Within a group the points are sorted by 'x', duplicates are kept, and a group needs at least two points to form a polygon (smaller groups are skipped with a warning). 'ymin' and 'ymax' may be given in either order: the band is drawn between them. 'alpha' (between 0 and 1), 'border', 'lty' and 'lwd' are layer-wide single values; 'fill' (or 'col') sets the interior and can be a constant or a mapping.
When the layer brings its own data, inherited mappings are still evaluated on that data: give the layer the variables it inherits, or set 'inherit = FALSE' when the plot has aesthetics the band does not carry.
'bb_smooth()' fits an explicit model per group and draws the fitted curve, optionally with a confidence band. The fit method is never implicit: choose '"lm"' or '"loess"' (the default), pass extra fitting arguments through 'method.args', and control the band with 'se' and 'level'.
‘x' and 'y' are mapped from the layer’s data, 'group' splits the fit, and a mapped 'col' colours each curve. The 'formula' response must be 'y'; transform the data or the mapping rather than the response, so the band stays on the drawn scale. The confidence band uses 'fill' (or the curve colour at low alpha). Small samples that cannot support the requested fit are reported with a warning and fall back to a linear fit; a group with fewer than two points is skipped. Fits are computed when the layer is added, so repeated draws do not re-fit.
'bb_violin()' draws one density polygon per group: 'x' selects the group (a factor, character or numeric position), 'y' is the numeric variable whose distribution is estimated with 'stats::density()'. The density is scaled to 'width' in x units, so groups stay comparable; 'adjust' and 'bw' control the bandwidth, 'kernel', 'trim' and 'n' are passed to 'density()'.
The layer follows the grammar contract: it inherits data and mapping, accepts its own, draws in '+' order, honours constant or mapped 'fill'/'col', and contributes the group positions and the numeric values to the ranges. With 'orientation = "horizontal"', map 'x' to the numeric values and 'y' to the groups; the default vertical orientation is the other way round. A group needs at least two finite values and a non-zero spread; other groups are skipped with a warning. Rows with a non-finite value are dropped.
A modified bbplot object
A modified bbplot object
A modified bbplot object
A modified bbplot object
A modified bbplot object
A modified bbplot object
A modified bbplot object
A modified bbplot object
A modified bbplot object
Guangchuang Yu
library(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point() + bb_lm(bb_aes(group=cyl), lwd=2)library(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point() + bb_lm(bb_aes(group=cyl), lwd=2)
Build a plot without drawing it
bb_build(plot)bb_build(plot)
plot |
a |
'bb_build()' performs the computation that 'print()' would perform, without opening a device and without drawing: it trains the scales, resolves the mappings, collects each layer's data and computes the limits (and the per-panel limits of a faceted plot). The result is an ordinary list, meant for inspection and for checking a plot before it is rendered.
The build is side-effect free with respect to graphics: it does not call 'plot()', does not change 'par()' and does not touch '.Random.seed' (jitter is applied when the plot is drawn, not when it is built). Training stores the trained scales in the plot's internal environment; that is plot state, not graphics state. Repeated calls on the same object return the same structure and limits.
A list with data, mapping (labels), layers
(name, kind, data, mapping labels, inherit, parameter names), scales
(trained), limits, panels (NULL or one entry per
facet with its key, row count and limits), labs, position
(the positional-scale summary), facet (a serializable summary:
variables, scales, nrow, ncol and free_colour) and warnings
collected while building.
p <- bbplot(mtcars, bb_aes(mpg, disp, col = factor(cyl))) + bb_point() str(bb_build(p), max.level = 2)p <- bbplot(mtcars, bb_aes(mpg, disp, col = factor(cyl))) + bb_point() str(bb_build(p), max.level = 2)
Flip the positional axes
bb_coord_flip()bb_coord_flip()
'bb_coord_flip()' swaps the x and y axes. It is a coordinate operation, not a data transformation: axes labels, positional scales and the titles swap, and the supported layers are redrawn with x/y swapped.
Supported layers are 'bb_point()', 'bb_line()', 'bb_text()', 'bb_segment()', 'bb_tile()', 'bb_layer()', 'bb_violin()', 'bb_boxplot()', 'bb_bar()', 'bb_errorbar()', 'bb_ribbon()', 'bb_density()', 'bb_hist()' and 'bb_smooth()' (these switch to the opposite 'orientation'), plus constant or mapped 'bb_hline()'/'bb_vline()' (which become the other reference line). Layers that have no orientation model ('bb_lm()', 'bb_signif()') raise an error rather than drawing in the wrong orientation.
A modified bbplot object
Guangchuang Yu
Facet a bbplot object into a row/column grid.
bb_facet_grid( rows = NULL, cols = NULL, scales = "fixed", labeller = NULL, drop = TRUE, strip_width = NULL, free_colour = FALSE )bb_facet_grid( rows = NULL, cols = NULL, scales = "fixed", labeller = NULL, drop = TRUE, strip_width = NULL, free_colour = FALSE )
rows |
a one-sided formula for the row variable, e.g. |
cols |
a one-sided formula for the column variable, e.g. |
scales |
scale behavior across panels, one of 'fixed', 'free', 'free_x', or 'free_y'. With free scales, x is shared within a column and y within a row, matching the grid layout. |
labeller |
optional function applied to each row/column key. |
drop |
if FALSE, unused factor levels still get panels. |
strip_width |
optional positive integer; wraps long strip labels. |
free_colour |
if TRUE, each panel trains its own col/fill domain from its rows (requires an explicit colour scale; an outside legend is then an error because it cannot describe several domains). |
At least one of rows and cols is required. Panels are
the full combination of the row and column keys; a combination without
rows is drawn empty rather than skipped. Row labels are placed at the
right, column labels at the top. For bb_build(), each panel is
reported with its row and column key, label, row count and limits.
A modified bbplot object
Guangchuang Yu
Facet a bbplot object into multiple panels.
bb_facet_wrap( facets, ncol = NULL, nrow = NULL, scales = "fixed", labeller = NULL, drop = TRUE, strip_width = NULL, free_colour = FALSE )bb_facet_wrap( facets, ncol = NULL, nrow = NULL, scales = "fixed", labeller = NULL, drop = TRUE, strip_width = NULL, free_colour = FALSE )
facets |
a formula specifying faceting variable, e.g. |
ncol |
number of columns. |
nrow |
number of rows. |
scales |
scale behavior across facets, one of 'fixed', 'free', 'free_x', or 'free_y'. |
labeller |
optional function applied to each panel key; the result is the strip label. |
drop |
if FALSE, unused factor levels still get a panel. Such a panel has no rows and falls back to the global limits, including on free scales. |
strip_width |
optional positive integer; wraps long strip labels with
|
free_colour |
if TRUE, each panel trains its own col/fill domain from its rows (requires an explicit colour scale; an outside legend is then an error because it cannot describe several domains). |
nrow and ncol must be positive integers, and their
product must be at least the number of panels; a layout that is too small is
reported instead of silently overwriting a panel. By default facets are built
from the keys that occur in the data, so unused factor levels do not create
empty panels; set drop = FALSE to keep them.
A modified bbplot object
Guangchuang Yu
add grid lines
bb_grid(col = "lightgray", lty = par("lty"), lwd = par("lwd"), bg = TRUE)bb_grid(col = "lightgray", lty = par("lty"), lwd = par("lwd"), bg = TRUE)
col |
line color |
lty |
line type |
lwd |
line width |
bg |
whether plot the grid lines as background |
A modified bbplot object
Guangchuang Yu
Resolve the grouping values of a statistical layer
bb_group_values(mapping, data, x = NULL)bb_group_values(mapping, data, x = NULL)
mapping |
the effective aesthetic mapping |
data |
the layer data |
x |
optional x values; used when they are a factor or character |
The one grouping rule used by the statistical layers: an explicit 'group' mapping wins, then a discrete 'x', then a mapped 'col', then a mapped 'fill'. Custom statistical layers can call this function so they group like the built-in ones.
A vector of group values, or NULL when there is no grouping
Guangchuang Yu
change labels for bbplot
bb_labs(title = NULL, sub = NULL, xlab = NULL, ylab = NULL) bb_title(title) bb_sub(sub) bb_xlab(xlab) bb_ylab(ylab)bb_labs(title = NULL, sub = NULL, xlab = NULL, ylab = NULL) bb_title(title) bb_sub(sub) bb_xlab(xlab) bb_ylab(ylab)
title |
title |
sub |
sub |
xlab |
xlab |
ylab |
ylab |
setting one or several of 'title', 'sub', 'xlab', and 'ylab'
A modified bbplot object
Guangchuang Yu
library(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point(pch=19) p + bb_labs(title = "hello", sub = "just for demo", xlab="this is xlab", ylab = "this is ylab") + bb_title("hello world") # last one ruleslibrary(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point(pch=19) p + bb_labs(title = "hello", sub = "just for demo", xlab="this is xlab", ylab = "this is ylab") + bb_title("hello world") # last one rules
build a custom layer
bb_layer( draw, mapping = NULL, data = NULL, inherit = TRUE, ..., name = "custom layer", limits = NULL, aesthetics = NULL, summary = FALSE, range = NULL )bb_layer( draw, mapping = NULL, data = NULL, inherit = TRUE, ..., name = "custom layer", limits = NULL, aesthetics = NULL, summary = FALSE, range = NULL )
draw |
a function that draws the layer. Its first arguments are
|
mapping |
aesthetic mapping for this layer. Defaults to inheriting the plot mapping. |
data |
layer data. Defaults to the plot data. |
inherit |
whether to inherit the plot mapping, see |
... |
fixed aesthetics and any other values passed to |
name |
shown when the plot's layers are printed. |
limits |
optional range the drawing function needs, as
|
aesthetics |
optional mapped aesthetics the layer understands; include
|
summary |
logical; TRUE when the layer computes its own coordinates and the plot-level x/y should not be added to the ranges. |
range |
optional function |
'bb_layer()' is the supported way to add your own drawing code to a 'bbplot'. It is an ordinary layer: it inherits the plot data and mapping, accepts its own 'data' and 'mapping', is drawn in '+' order, and takes part in the same input validation as the built-in layers.
The drawing function receives the resolved coordinates and, when the layer has mappings, the mapped aesthetics, plus whatever fixed aesthetics you pass through '...':
bb_layer(function(x, y, col, ...) { ... }, col = "tomato")
A custom layer takes part in the ranges of its mapped 'x'/'y' values, like
the built-in layers, and its 'data' follows the 'bb_facet_wrap()' panels.
Coordinates that the drawing function computes itself (a smooth curve, a
confidence band, a reference line) do not widen the axes on their own; pass
them explicitly in 'limits', or supply a 'range' function for a statistical
layer. Mapped aesthetics ('col', 'fill', 'pch', 'lty', 'cex') use the shared
scale and the automatic legend; a custom layer cannot define a new scale or
legend type. If the drawing needs a different scale, use the public scale
constructors or start from a canvas created by as.bbplot().
A layer object to be added to a bbplot with +.
library(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col = factor(cyl))) p + bb_layer(function(x, y, col, cex = 1, ...) { graphics::points(x = x, y = y, col = col, pch = 19, cex = cex) }, cex = 1.6) ## a reference line below the data needs the axis to make room for it p + bb_point(pch = 19) + bb_layer(function(x, y, ...) { graphics::abline(h = min(y) - 50, col = "firebrick", lty = 2) }, limits = list(y = range(mtcars$disp) + c(-60, 0)))library(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col = factor(cyl))) p + bb_layer(function(x, y, col, cex = 1, ...) { graphics::points(x = x, y = y, col = col, pch = 19, cex = cex) }, cex = 1.6) ## a reference line below the data needs the axis to make room for it p + bb_point(pch = 19) + bb_layer(function(x, y, ...) { graphics::abline(h = min(y) - 50, col = "firebrick", lty = 2) }, limits = list(y = range(mtcars$disp) + c(-60, 0)))
Add legend for aesthetic mapping.
bb_legend( position = "topright", title = NULL, aesthetic = "col", pch = 19, bty = "n", outside = FALSE, orientation = c("vertical", "horizontal"), layer = NULL, style = c("auto", "bar"), title_width = NULL, width = 1.4, ... )bb_legend( position = "topright", title = NULL, aesthetic = "col", pch = 19, bty = "n", outside = FALSE, orientation = c("vertical", "horizontal"), layer = NULL, style = c("auto", "bar"), title_width = NULL, width = 1.4, ... )
position |
legend position passed to |
title |
legend title. |
aesthetic |
currently supports |
pch |
point shape used in legend. |
bty |
box type passed to |
outside |
logical, whether to place the legend outside the plotting area. |
orientation |
orientation of a continuous colour bar,
|
layer |
optional layer index or name: the legend then describes that layer's mapping. The colour scale is still the shared one, so this selects the mapping/title, not a separate domain. |
style |
|
title_width |
optional positive integer; wraps a long legend title. |
width |
relative width of an outside legend column (default 1.4). |
... |
additional parameters passed to |
A modified bbplot object
Guangchuang Yu
jitter position for bb_point
bb_position(..., type = c("jitter", "identity"))bb_position(..., type = c("jitter", "identity"))
... |
parameters for the position, e.g. |
type |
position type, one of 'identity' or 'jitter'. |
a position object that can be passed to bb_point().
Guangchuang Yu
Save a plot to a file
bb_save( plot, filename, width = 7, height = 5, units = "in", res = 300, bg = "white", device = NULL, overwrite = FALSE, ... )bb_save( plot, filename, width = 7, height = 5, units = "in", res = 300, bg = "white", device = NULL, overwrite = FALSE, ... )
plot |
a |
filename |
output file |
width, height
|
device size |
units |
one of |
res |
resolution for raster devices |
bg |
background colour |
device |
optional device name ( |
overwrite |
whether an existing file may be replaced |
... |
additional arguments passed to the device |
'bb_save()' draws into a temporary file next to the target and moves it into place only after the plot has been drawn. It never closes a device the caller had already open, and on failure it closes its own device, keeps the original error, removes the temporary file and leaves an existing target untouched (even when 'overwrite = TRUE').
The device is chosen from the file extension ('pdf', 'png', 'jpeg'/'jpg', 'tiff'/'tif', 'svg') unless 'device' is given. Supplying a device that conflicts with a known extension is an error. Vector devices take their size in inches; raster devices take 'width', 'height', 'units' and 'res'.
An existing file is never overwritten unless 'overwrite = TRUE'. A missing directory is an error.
The file name, invisibly
p <- bbplot(mtcars, bb_aes(mpg, disp)) + bb_point() f <- tempfile(fileext = ".pdf") bb_save(p, f) unlink(f)p <- bbplot(mtcars, bb_aes(mpg, disp)) + bb_point() f <- tempfile(fileext = ".pdf") bb_save(p, f) unlink(f)
change col palette
bb_scale_col_palette( palette = NULL, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_col_manual( values, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_col_gradient( low = "#132B43", high = "#56B1F7", limits = NULL, na.value = "grey50", oob = c("squish", "censor"), breaks = NULL, labels = NULL, minor_breaks = NULL )bb_scale_col_palette( palette = NULL, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_col_manual( values, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_col_gradient( low = "#132B43", high = "#56B1F7", limits = NULL, na.value = "grey50", oob = c("squish", "censor"), breaks = NULL, labels = NULL, minor_breaks = NULL )
palette |
color palette |
limits |
optional limits of the trained domain. Values outside the limits follow 'oob'; levels outside the limits are not shown. |
na.value |
colour used for missing values and for values not covered by a discrete scale. |
drop |
whether unobserved factor levels are dropped from the trained scale and the legend. |
breaks |
optional breaks for a continuous colour bar. Defaults to 'pretty()' on the trained domain. |
labels |
optional labels for the breaks (continuous) or a named vector renaming discrete levels. |
minor_breaks |
optional positions for minor ticks on a continuous colour bar; 'NULL' uses the midpoints between the major breaks. |
values |
colors for discrete scale. |
low |
low color for continuous scale. |
high |
high color for continuous scale. |
oob |
out-of-bounds behaviour for a continuous scale: '"squish"' (default) clamps to the limits, '"censor"' maps them to 'na.value'. |
A modified bbplot object
Guangchuang Yu
Fill scales
bb_scale_fill_palette( palette = NULL, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_fill_manual( values, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_fill_gradient( low = "#132B43", high = "#56B1F7", limits = NULL, na.value = "grey50", oob = c("squish", "censor"), breaks = NULL, labels = NULL, minor_breaks = NULL )bb_scale_fill_palette( palette = NULL, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_fill_manual( values, limits = NULL, na.value = "grey50", drop = TRUE, breaks = NULL, labels = NULL, minor_breaks = NULL ) bb_scale_fill_gradient( low = "#132B43", high = "#56B1F7", limits = NULL, na.value = "grey50", oob = c("squish", "censor"), breaks = NULL, labels = NULL, minor_breaks = NULL )
palette |
color palette |
limits |
optional limits of the trained domain. Values outside the limits follow 'oob'; levels outside the limits are not shown. |
na.value |
colour used for missing values and for values not covered by a discrete scale. |
drop |
whether unobserved factor levels are dropped from the trained scale and the legend. |
breaks |
optional breaks for a continuous colour bar. Defaults to 'pretty()' on the trained domain. |
labels |
optional labels for the breaks (continuous) or a named vector renaming discrete levels. |
minor_breaks |
optional positions for minor ticks on a continuous colour bar; 'NULL' uses the midpoints between the major breaks. |
values |
colors for discrete scale. |
low |
low color for continuous scale. |
high |
high color for continuous scale. |
oob |
out-of-bounds behaviour for a continuous scale: '"squish"' (default) clamps to the limits, '"censor"' maps them to 'na.value'. |
'fill' is a separate aesthetic from 'col': use these constructors when a layer maps 'fill' ('bb_tile()', 'bb_density()', 'bb_bar()', 'bb_boxplot()'). They take the same arguments as the 'col' scales.
aesthetic scales
bb_scale_pch_manual(values, limits = NULL, na.value = 1, drop = TRUE) bb_scale_lty_manual(values, limits = NULL, na.value = 1, drop = TRUE) bb_scale_cex_manual(values, limits = NULL, na.value = 1, drop = TRUE) bb_scale_cex_continuous( range = c(0.8, 1.6), limits = NULL, na.value = 1, oob = c("squish", "censor") )bb_scale_pch_manual(values, limits = NULL, na.value = 1, drop = TRUE) bb_scale_lty_manual(values, limits = NULL, na.value = 1, drop = TRUE) bb_scale_cex_manual(values, limits = NULL, na.value = 1, drop = TRUE) bb_scale_cex_continuous( range = c(0.8, 1.6), limits = NULL, na.value = 1, oob = c("squish", "censor") )
values |
values used for mapping. |
limits |
optional limits of the trained domain. |
na.value |
value used for missing values. |
drop |
whether unobserved levels are dropped. |
range |
numeric length-2 range for continuous mapping. |
oob |
out-of-bounds behaviour, '"squish"' or '"censor"'. |
A modified bbplot object
Guangchuang Yu
Positional scales
bb_scale_x_continuous( limits = NULL, breaks = NULL, labels = NULL, trans = c("identity", "log10") ) bb_scale_y_continuous( limits = NULL, breaks = NULL, labels = NULL, trans = c("identity", "log10") ) bb_scale_x_log10(limits = NULL, breaks = NULL, labels = NULL) bb_scale_y_log10(limits = NULL, breaks = NULL, labels = NULL) bb_scale_x_date( limits = NULL, breaks = NULL, labels = NULL, format = "%Y-%m-%d" ) bb_scale_y_date( limits = NULL, breaks = NULL, labels = NULL, format = "%Y-%m-%d" )bb_scale_x_continuous( limits = NULL, breaks = NULL, labels = NULL, trans = c("identity", "log10") ) bb_scale_y_continuous( limits = NULL, breaks = NULL, labels = NULL, trans = c("identity", "log10") ) bb_scale_x_log10(limits = NULL, breaks = NULL, labels = NULL) bb_scale_y_log10(limits = NULL, breaks = NULL, labels = NULL) bb_scale_x_date( limits = NULL, breaks = NULL, labels = NULL, format = "%Y-%m-%d" ) bb_scale_y_date( limits = NULL, breaks = NULL, labels = NULL, format = "%Y-%m-%d" )
limits |
optional two limits for the axis. |
breaks |
optional break positions; 'NULL' uses the base axis. |
labels |
optional labels for the breaks; requires 'breaks'. |
trans |
axis transform: '"identity"' or '"log10"'. |
format |
date format for a date axis. |
These scales control the x and y axes: user limits, breaks, labels, a log10 transform ('bb_scale_x_log10()', 'bb_scale_y_log10()') and date axes ('bb_scale_x_date()', 'bb_scale_y_date()'). They are separate from the aesthetic scales ('col', 'fill', 'pch', 'lty', 'cex').
'limits' sets the final axis range; values outside it are clipped by the device. A log scale requires positive limits. Date scales use 'graphics::axis.Date()' and take Date limits/breaks.
A modified bbplot object
Guangchuang Yu
bbplot theme
bb_theme(...) bb_theme_expand(...) bb_theme_grey(...) bb_theme_deepblue(...) bb_theme_bw(...) bb_theme_minimal(...)bb_theme(...) bb_theme_expand(...) bb_theme_grey(...) bb_theme_deepblue(...) bb_theme_bw(...) bb_theme_minimal(...)
... |
parameters for graphics::par |
setting visual details of bbplot
A modified bbplot object
Guangchuang Yu
bbplot
bbplot(data, mapping = bb_aes(), auto_legend = TRUE)bbplot(data, mapping = bb_aes(), auto_legend = TRUE)
data |
data |
mapping |
variable mapping |
auto_legend |
if TRUE (the default), mapped aesthetics get outside legends automatically; explicit 'bb_legend()' components take over the aesthetics they name. |
a grammar of graphics built on base graphics. The bbplot class contains data (input data), mapping (aesthetic mapping), layer (a list of plot layers), theme (theme setting) and labs (label setting, including title, subtitle, x and y labels).
'+' adds components (layers, themes, labels, scales, legends, facets) to a
single plot and draws them in the order they were added. It does not
combine two complete plots: arrange several plots with
aplot::plot_list() instead.
Every layer inherits the plot data and mapping and may
override them: a local mapping overrides the global mapping aesthetic by
aesthetic, and inherit = FALSE opts out of the global mapping
entirely. Aesthetic constants such as bb_point(col = "tomato") apply
to the whole layer and win over a mapped aesthetic.
bbplot object
Guangchuang Yu
library(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) p + bb_grid(col='grey50', lty='dashed') + bb_point(pch=19)library(plotbb) p <- bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) p + bb_grid(col='grey50', lty='dashed') + bb_point(pch=19)
Add custom objects to bbplot
bbplot_add(object, plot)bbplot_add(object, plot)
object |
An object to add to the plot |
plot |
The bbplot object to add 'object' to |
This generic is the extension point for new kinds of components. A method
receives the object and the plot and must return the modified plot; it
should describe the resulting plot instead of drawing, and can rely on the
public bb_layer() (or the other public constructors) to add the
drawing.
A method must not draw directly, change the device or rely on internal
helpers such as build_layer(); those are implementation details and
are not part of the stable contract. Packages register the method with
S3method(bbplot_add, <class>) in their NAMESPACE. A component
added this way takes part in the + order and in the graphics-state
restoration like every other component, and it is re-applied to every facet
panel. The layers a method adds are not added a second time when a panel is
rebuilt: the owning component is re-run instead.
A modified bbplot object
Guangchuang Yu
bb_note <- function(label) { structure(list(label = label), class = "bb_note") } bbplot_add.bb_note <- function(object, plot) { plot + bb_layer(function(x, y, ...) { graphics::text(mean(range(x)), mean(range(y)), object$label) }) } bbplot(mtcars, bb_aes(mpg, disp)) + bb_point(pch = 19) + bb_note("a third-party component")bb_note <- function(label) { structure(list(label = label), class = "bb_note") } bbplot_add.bb_note <- function(object, plot) { plot + bb_layer(function(x, y, ...) { graphics::text(mean(range(x)), mean(range(y)), object$label) }) } bbplot(mtcars, bb_aes(mpg, disp)) + bb_point(pch = 19) + bb_note("a third-party component")
set bb_theme
set_bb_theme(theme)set_bb_theme(theme)
theme |
bb_theme |
setting bb_theme for ordinary base plot command. It internally use par to set global graphic parameters. Users need to explictely call unset_bb_theme() to restore original setting.
Themes are single-level: calling 'set_bb_theme()' while a theme is already active replaces it without losing the original graphics parameters, so 'unset_bb_theme()' always restores the state from before the *first* call. Prefer 'with_bb_theme()' when the theme should be scoped to a block of code.
setting selected theme as default (has side effect and will affect other base plot)
Guangchuang Yu
library(plotbb) set_bb_theme(bb_theme_deepblue) bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point(pch=19) unset_bb_theme()library(plotbb) set_bb_theme(bb_theme_deepblue) bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point(pch=19) unset_bb_theme()
unset bb_theme
unset_bb_theme()unset_bb_theme()
remove all the themes by set_bb_theme. The saved pre-theme graphics parameters are discarded afterwards, so the function is safe to call repeatedly.
unset theme (i.e., restore par setting)
Guangchuang Yu
Run code with a theme applied to the current device
with_bb_theme(theme, code)with_bb_theme(theme, code)
theme |
a 'bb_theme' object or a function returning one. |
code |
an expression to evaluate. |
'with_bb_theme()' applies 'theme' with 'par()' for the duration of 'code' and restores the previous graphics parameters afterwards, including when 'code' signals an error. Nothing is stored in options, so it can be nested and does not interact with 'set_bb_theme()'.
the value of 'code', invisibly.
Guangchuang Yu
library(plotbb) with_bb_theme(bb_theme_deepblue(), { bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point(pch=19) })library(plotbb) with_bb_theme(bb_theme_deepblue(), { bbplot(mtcars, bb_aes(mpg, disp, col=factor(cyl))) + bb_point(pch=19) })