| Title: | Descriptive Statistics Graphics and Utilities |
| Version: | 0.1.6 |
| Description: | Draws the statistical graphics of the 'DescToolsX' ecosystem on top of base graphics: distribution and density displays, bivariate and categorical plots, diagnostic and model evaluation panels, and a faceting mechanism for arranging them. A theme system resolves colours, symbols and layout centrally, so a consistent look can be set once rather than repeated at every call. The package also contains the colour conversion and palette tools, the geometry helpers, the number and string formatting routines and the HTML output utilities that the plots are built from. It is self contained and usable without the rest of the suite. |
| Depends: | R (≥ 4.6.0) |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| Encoding: | UTF-8 |
| LinkingTo: | Rcpp |
| Imports: | Rcpp, bedrock (≥ 0.1.18), MASS, cli, withr, stringi, methods, base64enc, grid |
| Suggests: | testthat (≥ 3.0.0), R.rsp, hexbin, prettyunits, pdftools |
| Config/testthat/edition: | 3 |
| VignetteBuilder: | R.rsp |
| URL: | https://andrisignorell.github.io/pharos/, https://github.com/AndriSignorell/pharos/ |
| BugReports: | https://github.com/AndriSignorell/pharos/issues |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-03 23:02:06 UTC; andri |
| Author: | Andri Signorell |
| Maintainer: | Andri Signorell <andri@signorell.net> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-25 12:20:02 UTC |
Formula Interface – Common Arguments
Description
Common formula-based interface shared by multiple functions.
Arguments
formula |
A formula of the form |
data |
an optional matrix or data frame (or similar; see
|
subset |
an optional vector specifying a subset of observations to be used in the analysis. |
na.action |
A function which indicates what should happen when
the data contain |
Details
Formula interfaces are evaluated using stats::model.frame(),
following standard R conventions.
The left-hand side of the formula must contain the response variable.
The right-hand side typically specifies a grouping or explanatory variable.
Only formulas with a single response and at least one explanatory
variable are supported.
See also:
Metric Prefixes
Description
SI metric prefixes from yotta (10^{24}) down to yocto
(10^{-24}), with their name, symbol and multiplier. Used as default
lookup table by convUnit and for SI-prefix formatting in
fm.
Usage
Prefix
Format
A data.frame with 20 rows and 3 columns:
- pref
character, name of the prefix (e.g."kilo").- abbr
character, symbol of the prefix (e.g."k");"u"is used for micro.- mult
numeric, multiplier, i.e. the power of ten the prefix stands for (e.g.1000).
Value
A data.frame as described under Format; the object
is a constant, not a function.
Examples
Prefix
Prefix[Prefix$abbr == "k", ]
Coordinates for Named Plot Positions
Description
Returns the xy-coordinates and text-adjustment values for named anchor
positions such as "topleft", "center", etc., as used by
legend(). Useful for placing text or other annotations at
consistent, region-aware positions.
Usage
abcCoords(
x = "topleft",
region = c("plot", "figure", "device"),
cex = NULL,
inset = 0
)
Arguments
x |
A character string specifying the anchor position. One
of |
region |
one of |
cex |
character expansion factor. If |
inset |
inset distance from the boundary, specified in lines of
text (character heights/widths). May be a scalar (applied to both
x and y) or a length-2 vector (x inset, y inset). Default |
Details
The positioning logic is adapted from legend().
The inset is computed in character units via strwidth() and
strheight(), making it robust to device resizing, font
changes, and plot-range scaling.
Three regions are supported:
"plot"The inner plot area (
par("usr")). The default, and the regionlegend()positions in."figure"The figure region within the device, accounting for
par("fig")."device"The full device area.
Coordinates for "figure" and "device" lie outside
par("usr") and are therefore clipped away by text()
and friends unless the drawing call sets xpd = NA. The returned
values are in user space either way; only the clipping has to be turned
off by the caller.
Value
A list with two components:
xyA list with elements
xandygiving the anchor coordinates in user space.adjA numeric vector of length 2, suitable for the
adjargument oftext().
See Also
Other graphics.layout:
axTicksPosixct(),
axisBreak(),
isValidPlotRegion(),
lineToUser(),
mar(),
plotFacet(),
spreadOut()
Examples
plot(x = rnorm(10), type = "n", xlab = "", ylab = "")
# coordinates only
abcCoords("bottomleft")
# place text at a named position
xy <- abcCoords("bottomleft")
text(x = xy$xy$x, y = xy$xy$y, labels = "My Label", adj = xy$adj)
# all nine positions with inset
sapply(c("topleft", "top", "topright",
"left", "center", "right",
"bottomleft", "bottom", "bottomright"),
function(p) {
xy <- abcCoords(p, inset = 1)
text(x = xy$xy$x, y = xy$xy$y,
labels = p, adj = xy$adj)
})
# the margins need xpd = NA, whatever the coordinates say
xy <- abcCoords("bottomright", region = "figure", inset = 0.5)
text(x = xy$xy$x, y = xy$xy$y, labels = "source: ...",
adj = xy$adj, cex = 0.7, xpd = NA)
Add an Alpha Channel to Colors
Description
Add transparency to colors.
Usage
addOpacity(col, opacity = 0.5)
Arguments
col |
vector of valid R colors |
opacity |
opacity value between 0 and 1 |
Value
Character vector of hexadecimal colors with alpha channel.
See Also
Other color.manipulation:
colToOpaque(),
darken(),
fade(),
lighten(),
mixCol()
Examples
op <- par(no.readonly = TRUE)
addOpacity("yellow", 0.2)
addOpacity(2, 0.5) # red
canvas(3)
polygonX(circle(x=c(-1,0,1), y=c(1,-1,1), radius=2),
col=addOpacity(2:4, 0.4))
x <- rnorm(15000)
par(mfrow=c(1,2))
plot(x, type="p", col="blue" )
plot(x, type="p", col=addOpacity("blue", .2),
main="Better insight with alpha channel" )
par(op)
Arc Geometry
Description
Create one or more circular or elliptic arcs.
Usage
arc(
x = 0,
y = 0,
radiusX = 1,
radiusY = radiusX,
startAngle = 0,
endAngle = 2 * pi,
nPoints = 100
)
Arguments
x, y |
coordinates of the arc centre |
radiusX, radiusY |
horizontal and vertical radius |
startAngle, endAngle |
start and end angle in radians |
nPoints |
number of points used to approximate the arc |
Value
An object inheriting from class "arcGeometry".
See Also
Other geometry.structures:
band(),
bezier(),
circle(),
ellipse(),
polygonX(),
regPolygon(),
ring()
Examples
canvas(xlim = c(-2, 2))
# a quarter of a circle
lines(arc(radiusX = 1.5, startAngle = 0, endAngle = pi/2), lwd = 2)
# elliptic arcs, vectors of radii yield a collection of arcs
a <- arc(radiusX = c(0.5, 1), radiusY = c(1, 1.8),
startAngle = pi, endAngle = 3*pi/2)
lines(a, col = "red")
Confidence Interval Objects
Description
Converts common confidence interval representations into a standardized
object of class "CI". The standardized representation removes the
ambiguity between ordinary numeric data and confidence interval data.
Usage
as.CI(x, ...)
## S3 method for class 'matrix'
as.CI(x, ...)
## S3 method for class 'data.frame'
as.CI(x, estimate = "est", lower = "lci", upper = "uci", ...)
## S3 method for class 'list'
as.CI(x, ...)
## S3 method for class 'CI'
as.CI(x, ...)
## Default S3 method:
as.CI(x, ...)
isCI(x)
Arguments
x |
object to convert or, for |
... |
further arguments passed to methods |
estimate |
name of the data-frame column containing the point estimates |
lower |
name of the data-frame column containing the lower confidence limits |
upper |
name of the data-frame column containing the upper confidence limits |
Details
A "CI" object is a data frame containing the columns est,
lci, and uci. Additional columns are retained and can be used
as grouping variables by functions such as plotDot().
The primary purpose of as.CI() is to declare explicitly that an
object contains estimates and confidence limits. For example, a numeric
matrix with three columns is normally ambiguous: its columns may represent
three groups or the estimate, lower limit, and upper limit. Passing the
matrix to as.CI() declares that its columns have the latter meaning.
Supported inputs are:
a numeric matrix with exactly three columns, interpreted in the order
est,lci, anducia data frame containing columns for the estimates and confidence limits; their names can be specified with
estimate,lower, anduppera list in which every element contains three values representing
c(est, lci, uci)an array-like result from
tapply()in which every cell containsc(est, lci, uci); its dimensions are converted to grouping variablesan existing
"CI"object, which is returned unchanged
The standardized object can be passed directly to plotDot() to
display the estimates and their confidence intervals. This is particularly
useful for matrices, because a bare matrix supplied to plotDot() is
interpreted as grouped estimates rather than as confidence interval data.
Value
as.CI() returns a data frame of class "CI" containing
the columns est, lci, and uci, followed by any
grouping columns; isCI() returns a single logical value
See Also
Examples
# matrix containing estimate, lower limit, and upper limit
x <- matrix(
c(
10, 20, 30,
8, 18, 28,
12, 22, 32
),
ncol = 3,
dimnames = list(
c("A", "B", "C"),
c("est", "lci", "uci")
)
)
ci <- as.CI(x)
ci
isCI(ci)
# display the estimates and confidence intervals
plotDot(ci)
# data frame using the standard column names
d <- data.frame(
est = c(10, 20),
lci = c(8, 18),
uci = c(12, 22),
sex = c("F", "M")
)
as.CI(d)
# data frame using different column names
d <- data.frame(
item = c("A", "B"),
estimate = c(10, 20),
lower = c(8, 18),
upper = c(12, 22)
)
as.CI(
d,
estimate = "estimate",
lower = "lower",
upper = "upper"
)
# confidence intervals returned by tapply(): every cell holds the
# estimate and its limits (as e.g. lumen::meanCI() returns them)
meanCI <- function(z) {
ci <- t.test(z)$conf.int
c(est = mean(z), lci = ci[1], uci = ci[2])
}
xci <- with(
warpbreaks,
tapply(
breaks,
list(wool, tension),
meanCI
)
)
as.CI(xci)
plotDot(as.CI(xci))
Link to a self-contained embedded file
Description
Turns a file into a download link that carries the file with it: the
contents travel base64-encoded inside the href, so the resulting
HTML needs no server and no accompanying assets. The counterpart of
asImg() for non-image files – a data set next to a table,
a script next to its output.
Usage
asFileLink(path, label = NULL, type = NULL)
Arguments
path |
path to an existing file |
label |
link text; defaults to the file name |
type |
MIME type; guessed from the extension when |
Details
Browsers limit the size of a data URI, so this suits spreadsheets and text files rather than large binaries.
Value
an object of class c("html", "character")
See Also
Other html:
asHtml(),
asImg(),
embedFile(),
escapeHtml(),
htmlNotation,
htmlSubscript,
preview(),
preview.html(),
toHtmlTable()
Examples
fn <- tempfile(fileext = ".csv")
write.csv(head(iris), fn, row.names = FALSE)
asFileLink(fn, label = "iris")
unlink(fn)
Mark a character vector as HTML
Description
Tags a character vector with the S3 class "html" so that it
prints via preview.html() as readable text instead of as
a raw character vector.
Usage
asHtml(x)
Arguments
x |
a character vector, typically containing HTML markup |
Value
x, with class "html" added
See Also
Other html:
asFileLink(),
asImg(),
embedFile(),
escapeHtml(),
htmlNotation,
htmlSubscript,
preview(),
preview.html(),
toHtmlTable()
Examples
asHtml("<b>bold</b>")
Embed a plot as an inline HTML image
Description
Evaluates a plotting expression in a temporary PNG device and returns
the resulting image as a self-contained, base64-encoded <img>
tag (class "html", see asHtml()), suitable for
embedding directly in HTML text – a report, a question, an e-mail.
Usage
asImg(expr, width = 520, height = 440, res = 96, ...)
Arguments
expr |
a plotting expression, evaluated once inside the device.
A character string is not accepted: pass the plotting code itself,
e.g. |
width, height |
size of the device in pixels |
res |
nominal resolution in dpi, which also scales the text: raise it for a larger picture with the same relative proportions |
... |
further arguments passed to |
Details
The expression is passed unevaluated and carries its own environment, so a plot built inside a function sees that function's local variables. Several statements are given in braces, as in the examples below.
Value
an object of class c("html", "character") containing an
<img> tag with a data:image/png;base64,... source
See Also
Other html:
asFileLink(),
asHtml(),
embedFile(),
escapeHtml(),
htmlNotation,
htmlSubscript,
preview(),
preview.html(),
toHtmlTable()
Examples
img <- asImg(plot(1:10))
# several statements, and local variables
f <- function(n) {
x <- seq_len(n)
asImg({
plot(x, x^2, type = "b")
abline(h = mean(x^2), lty = 2)
})
}
substr(f(10), 1, 30)
Compute Axis Tickmark Locations (For POSIXct Axis)
Description
Compute pretty tickmark locations, the same way as R does internally. By default, gives the at values which axis.POSIXct(side, x) would use.
Usage
axTicksPosixct(side, x, at, format, labels = TRUE, ...)
axTicksDate(side = 1, x, ...)
Arguments
side |
see graphics::axis |
x, at |
date-time or date object. |
format |
see base::strptime |
labels |
either a logical value specifying whether annotations are to be made at the tickmarks, or a vector of character strings to be placed at the tickpoints |
... |
further arguments to be passed from or to other methods |
Details
graphics::axTicks() has no implementation for POSIXct axis. This function fills
the gap.
Value
numeric vector of coordinate values at which axis tickmarks can be drawn.
See Also
graphics::axTicks(), graphics::axis.POSIXct()
Other graphics.layout:
abcCoords(),
axisBreak(),
isValidPlotRegion(),
lineToUser(),
mar(),
plotFacet(),
spreadOut()
Examples
with(beaver1, {
time <- strptime(paste(1990, day, time %/% 100, time %% 100),
"%Y %j %H %M")
plot(time, temp, type = "l") # axis at 4-hour intervals.
# now label every hour on the time axis
plot(time, temp, type = "l", xaxt = "n")
r <- as.POSIXct(round(range(time), "hours"))
axis.POSIXct(1, at = seq(r[1], r[2], by = "hour"), format = "%H")
# place the grid
abline(v=axTicksPosixct(1, at = seq(r[1], r[2], by = "hour"), format = "%H"),
col="grey", lty="dotted")
})
Place a Break Mark on an Axis
Description
Places a break mark on an axis on an existing plot.
Usage
axisBreak(
axis = 1,
breakpos = NULL,
pos = NA,
bgcol = "white",
breakcol = "black",
style = "slash",
brw = 0.02
)
Arguments
axis |
which axis to break |
breakpos |
where to place the break in user units |
pos |
position of the axis (see axis) |
bgcol |
the color of the plot background |
breakcol |
the color of the "break" marker |
style |
either ‘gap’, ‘slash’ or ‘zigzag’ |
brw |
break width relative to plot width |
Details
The ‘pos’ argument is not needed unless the user has specified a different position from the default for the axis to be broken.
Value
No return value, called for its side effect of drawing the break mark on the current plot.
Note
There is some controversy about the propriety of using discontinuous
coordinates for plotting, and thus axis breaks. Discontinuous coordinates
allow widely separated groups of values or outliers to appear without
devoting too much of the plot to empty space.
The major objection seems
to be that the reader will be misled by assuming continuous coordinates.
The ‘gap’ style that clearly separates the two sections of the plot is
probably best for avoiding this.
Based on code by Jim Lemon and Ben Bolker, adapted to conform to package standards
See Also
Other graphics.layout:
abcCoords(),
axTicksPosixct(),
isValidPlotRegion(),
lineToUser(),
mar(),
plotFacet(),
spreadOut()
Examples
plot(3:10, main="Axis break test")
# put a break at the default axis and position
axisBreak()
axisBreak(2, 2.9, style="zigzag")
Draw an Axis With Formatted or Rotated Labels
Description
A drop-in replacement for graphics::axis() that adds two conveniences:
tick labels can be formatted through fm() via the fmt argument,
and labels can be drawn at an arbitrary angle using srt (which
graphics::axis() itself ignores). When rotated labels are requested the
function also estimates the margin space they require and, optionally,
widens the corresponding plot margin so the labels are not clipped.
Usage
axisFmt(
side,
at = NULL,
fmt = NULL,
labels = TRUE,
srt = NULL,
adj = NULL,
estimateMar = TRUE,
...
)
Arguments
side |
integer specifying which side of the plot the axis is drawn on,
as in |
at |
numeric vector of tick positions. If |
fmt |
format specification passed to |
labels |
either a logical or a character vector of labels. If
|
srt |
numeric, the string rotation angle in degrees. If |
adj |
label justification passed to |
estimateMar |
logical. If |
... |
further arguments passed to both |
Details
The fmt argument is passed straight to fm() and therefore accepts
the full range of format specifications: a special short code (e.g.
"\%", "e", "eng", "p"), an ISO-8601 date
pattern (e.g. "MMM yyyy"), a Style object, a bare (named)
list treated as a style template (e.g. fmt = list(digits = 1, bigMark = " ")), or a function of x. See fm() for the details.
When srt is set, the axis line and ticks are drawn without labels
via graphics::axis(), and the labels are added separately with
graphics::text() using xpd = TRUE so they may extend into the
figure margin. The required margin width is estimated by projecting the
rotated label boxes onto the axis normal (see estimateMar).
Note that changing par("mar") after the plot region has been
established does not resize the existing region. When estimateMar
is TRUE the widened margin therefore mainly ensures enough device
space outside the plot region for the (xpd = TRUE) labels. For a
clean layout, set the margin before calling graphics::plot(); the
returned mar component reports the estimated requirement so a
calling routine can reserve the space in advance.
Value
invisibly, a list with components at (the tick positions
used) and mar (the estimated margin requirement in lines for the
rotated labels, or NA when srt is NULL).
Author(s)
Andri Signorell andri@signorell.net
See Also
graphics::axis, graphics::axTicks, graphics::text, fm
Examples
# formatted tick labels
plot(1:10, runif(10) * 1000, yaxt = "n", xaxt = "n")
axisFmt(2, fmt = list(digits = 0, bigMark = " "))
axisFmt(1, fmt = list(fmt = "%", digits = 1))
# rotated category labels (margin widened automatically)
plot(1:5, c(7, 6, 11, 5, 12), xaxt = "n", xlab = "")
axisFmt(1, at = 1:5, labels = paste("Category", LETTERS[1:5]), srt = 45)
Band Geometry
Description
Create a polygonal band from upper and lower boundaries.
Usage
band(x, y)
Arguments
x |
A vector or matrix of x coordinates. |
y |
A vector or matrix of y coordinates. If either |
Details
Typically used to represent confidence or prediction bands.
Value
An object inheriting from class
"bandGeometry".
See Also
Other geometry.structures:
arc(),
bezier(),
circle(),
ellipse(),
polygonX(),
regPolygon(),
ring()
Examples
set.seed(18)
x <- rnorm(15)
y <- x + rnorm(15)
new <- seq(-3, 3, 0.5)
pred <- predict(
lm(y ~ x),
newdata = data.frame(x = new),
interval = "confidence"
)
plot(y ~ x)
polygonX(
band(
x = new,
y = pred[,2:3]
),
col = addOpacity("grey80", 0.5),
border = NA
)
Place Value Labels on a Barplot
Description
It can sometimes make sense to display data values directly on the bars in a barplot. There are a handful of obvious alternatives for placing the labels, either on top of the bars, right below the upper end, in the middle or at the bottom. Determining the required geometry - although not difficult - is cumbersome and the code is distractingly long within an analysis code. The present function offers a short way to solve the task. It can place text either in the middle of the stacked bars, on top or on the bottom of a barplot (side by side or stacked).
Usage
barText(
height,
mids,
labels = height,
beside = FALSE,
horiz = FALSE,
cex = par("cex"),
adj = NULL,
pos = c("top-out", "top-in", "mid", "bottom-in", "bottom-out"),
offset = 0,
col = NULL,
...
)
Arguments
height |
either a vector or matrix of values describing the bars which make up the plot exactly as used for creating the barplot. |
mids |
the returned mid points as returned by |
labels |
the labels to be placed on the bars. |
beside |
a logical value. If |
horiz |
a logical value. If |
cex |
numeric character expansion factor; multiplied by
|
adj |
one or two values in |
pos |
one of |
offset |
a vector indicating how much the bars should be shifted relative to the x axis. |
col |
the color and to be used, possibly a vector (default in par("col")). |
... |
the dots are passed to the |
Details
The x coordinates of the labels can be found by using
barplot() result, if they are to be centered at the top of
each bar. barText() calculates the rest.
Notice that when the labels are placed on top of the bars, they may be
clipped. This can be avoided by setting xpd=TRUE.
Value
returns the geometry of the labels invisibly
See Also
Other graphics.annotation:
boxedText(),
colLegend(),
errBars(),
stamp(),
textLegend(),
titleRect()
Examples
# simple vector
x <- c(353, 44, 56, 34)
b <- barplot(x)
barText(x, b, x)
# more complicated
b <- barplot(VADeaths, horiz = FALSE, col="steelblue", beside = TRUE)
barText(VADeaths, mids=b, horiz = FALSE, beside = TRUE, cex=0.8)
barText(VADeaths, mids=b, horiz = FALSE, beside = TRUE, cex=0.8, pos="bottom-in",
col="white", font=2)
b <- barplot(VADeaths, horiz = TRUE, col="steelblue", beside = TRUE)
barText(VADeaths, mids=b, horiz = TRUE, beside = TRUE, cex=0.8)
b <- barplot(VADeaths)
barText(VADeaths, mids=b)
b <- barplot(VADeaths, horiz = TRUE)
barText(VADeaths, mids=b, horiz = TRUE, col="red", cex=1.5)
Bézier Geometry
Description
Create a Bézier curve from a set of control points.
Usage
bezier(x, y = NULL, nPoints = 100)
Arguments
x, y |
numeric vectors of control points.
Alternatively, |
nPoints |
number of points used to approximate the curve. |
Value
An object inheriting from class
"bezierGeometry".
References
Farin, G. (1993). Curves and Surfaces for Computer Aided Geometric Design. Academic Press.
See Also
Other geometry.structures:
arc(),
band(),
circle(),
ellipse(),
polygonX(),
regPolygon(),
ring()
Examples
canvas(xlim = c(0, 1))
lines(
bezier(
x = c(0, 0.5, 1),
y = c(0, 1, 0)
),
col = "red",
lwd = 2
)
Add Text in a Box to a Plot
Description
boxedText draws the strings given in the vector labels at the coordinates given by x and y, surrounded by a rectangle.
Usage
boxedText(x, ...)
## Default S3 method:
boxedText(
x,
y = NULL,
labels = NULL,
adj = NULL,
pos = NULL,
offset = 0.5,
vfont = NULL,
cex = 1,
col = NULL,
font = NULL,
srt = 0,
xPad = 0.2,
yPad = 0.2,
density = NULL,
angle = 45,
bg = NA,
border = par("fg"),
lty = par("lty"),
lwd = par("lwd"),
...
)
## S3 method for class 'formula'
boxedText(formula, data = parent.frame(), ..., subset)
Arguments
x, y |
numeric vectors of coordinates where the text labels should be written. If the length of x and y differs, the shorter one is recycled. |
... |
additional arguments are passed to the text function. |
labels |
a character vector or expression specifying the text to be written. An attempt is made to coerce other language objects (names and calls) to expressions, and vectors and other classed objects to character vectors by as.character. If labels is longer than x and y, the coordinates are recycled to the length of labels. |
adj |
the value of adj determines the way in which text strings are
justified. A value of 0 produces left-justified text, 0.5 (the default)
centered text and 1 right-justified text. (Any value in |
pos |
a position specifier for the text. If specified this overrides any adj value given. Values of 1, 2, 3 and 4, respectively indicate positions below, to the left of, above and to the right of the specified coordinates. |
offset |
when pos is specified, this value gives the offset of the label from the specified coordinate in fractions of a character width. |
vfont |
|
cex |
numeric character expansion factor; multiplied by
|
col, font |
the color and (if vfont = NULL) font to be used, possibly
vectors. These default to the values of the global graphical parameters in
|
srt |
the string rotation in degrees. |
xPad, yPad |
the proportion of the rectangles to the extent of the text within. |
density |
the density of shading lines, in lines per inch. The default
value of |
angle |
angle (in degrees) of the shading lines. |
bg |
color(s) to fill or shade the rectangle(s) with. The default
|
border |
color for rectangle border(s). The default is
|
lty |
line type for borders and shading; defaults to |
lwd |
line width for borders and shading. Note that the use of
|
formula |
A formula of the form |
data |
an optional matrix or data frame (or similar; see
|
subset |
an optional vector specifying a subset of observations to be used in the analysis. |
Value
No return value, called for its side effect of adding the boxed labels to the current plot.
See Also
similar function in package plotrix
plotrix::boxed.labels (lacking rotation option)
Other graphics.annotation:
barText(),
colLegend(),
errBars(),
stamp(),
textLegend(),
titleRect()
Examples
canvas(xpd=TRUE)
boxedText(0, 0, adj=0, label="This is boxed text", srt=seq(0,360,20),
xPad=.3, yPad=.3)
points(0,0, pch=15)
plot(mpg ~ hp, data=mtcars, type="n", main="MT cars mpg/hp (log-log)",
panel.first=quote(grid()), las=1, log="xy")
boxedText(mpg ~ hp, data=mtcars,
labels=rownames(mtcars), cex=0.6, border=FALSE, bg="grey90")
Canvas for Geometric Plotting
Description
This is just a wrapper for creating an empty plot with suitable defaults for plotting geometric shapes.
Usage
canvas(xlim = NULL, ylim = xlim, main = NULL, asp = 1, bg = "white", ...)
Arguments
xlim, ylim |
the xlims and ylims for the plot. Default is c(-1, 1). |
main |
the main title on top of the plot. |
asp |
numeric, giving the aspect ratio y/x. (See
|
bg |
the color of the user space of the plot, defaults to "white". |
... |
additional arguments are passed to the |
Details
The plot is created with these settings:
asp = 1, xaxt = "n", yaxt = "n", xlab = "", ylab = "", frame.plot = FALSE.
Value
a list of all the previous values of the parameters changed (returned invisibly)
See Also
Other graphics.setup:
polarGrid(),
setBackCol()
Examples
canvas(7)
text(0, 0, "Hello world!", cex=5)
Circle Geometry
Description
Create a circular geometry.
Usage
circle(x = 0, y = 0, radius = 1, nPoints = 100)
Arguments
x, y |
centre coordinates. |
radius |
circle radius. |
nPoints |
number of points used to approximate the circle. |
Value
An object inheriting from class "circleGeometry".
See Also
Other geometry.structures:
arc(),
band(),
bezier(),
ellipse(),
polygonX(),
regPolygon(),
ring()
Examples
canvas(xlim = c(-2, 2))
polygonX(circle(radius = 1.5), col = "lightblue")
# several circles at once
polygonX(circle(x = c(-0.6, 0.6), y = 0, radius = 0.4),
col = c("tomato", "royalblue"))
Convert CMY to CMYK
Description
Convert CMY colors to CMYK.
Usage
cmyToCmyk(col)
Arguments
col |
numeric CMY matrix. |
Value
Numeric CMYK matrix.
See Also
Examples
cmy <- rgbToCmy(c("#FF6347", "#4169E1"), maxColorValue = 255)
cmyToCmyk(cmy)
Convert CMYK to CMY
Description
Convert CMYK colors to CMY.
Usage
cmykToCmy(col)
Arguments
col |
numeric CMYK matrix. |
Value
Numeric CMY matrix.
See Also
Examples
cmy <- rgbToCmy(c("#FF6347", "#4169E1"), maxColorValue = 255)
cmyk <- cmyToCmyk(cmy)
# the way back
cmykToCmy(cmyk)
Convert CMYK to RGB
Description
Convert CMYK colors to RGB.
Usage
cmykToRgb(col, maxColorValue = 1)
Arguments
col |
numeric CMYK matrix (columns C, M, Y, K). |
maxColorValue |
maximum channel value. |
Value
Numeric RGB matrix.
See Also
Examples
cmyk <- cmyToCmyk(rgbToCmy(c("#FF6347", "#4169E1"), maxColorValue = 255))
cmykToRgb(cmyk)
# back to hexadecimal colors
rgbToHex(t(cmykToRgb(cmyk) * 255))
Add a Color Legend to a Plot
Description
Draw a color legend (color strip) inside an existing plot region.
Usage
colLegend(
x,
y = NULL,
col = rev(heat.colors(100)),
labels = NULL,
title = NULL,
width = NULL,
height = NULL,
horiz = FALSE,
xjust = 0,
yjust = 1,
inset = 0,
region = c("plot", "figure", "device"),
border = NA,
box = FALSE,
adj = NULL,
cex = 1,
...
)
Arguments
x |
left x-coordinate of the legend or a keyword specifying
automatic placement:
|
y |
top y-coordinate of the legend when |
col |
vector of colors. |
labels |
optional vector of labels, or a list holding the labels
(element
E.g. |
title |
optional title, or a list holding the title (element
|
width |
width of the legend in user coordinates. |
height |
height of the legend in user coordinates. |
horiz |
logical; if |
xjust |
horizontal justification. |
yjust |
vertical justification. |
inset |
inset distance(s) when keyword positioning is used. |
region |
character string specifying the reference region
used for keyword placement. One of:
|
border |
border color of individual color rectangles. |
box |
optional specification of an enclosing box around the whole legend. Can be:
|
adj |
text alignment passed to |
cex |
character expansion for labels. |
... |
additional arguments passed to |
Details
The legend can be positioned either by explicit coordinates or by
keyword placement such as "topright" or "left".
Labels may either be aligned with the edges of the color strip or centered within the color blocks.
Value
Invisibly returns a list with components:
- rect
-
List describing the color strip geometry with components
width,height,left, andtop. - text
-
List containing the label coordinates
xandy.
See Also
Other graphics.annotation:
barText(),
boxedText(),
errBars(),
stamp(),
textLegend(),
titleRect()
Examples
plot(1:15,, xlim=c(0,10), type="n", xlab="", ylab="", main="Colorstrips")
# A
colLegend(x="right", inset=5, labels=c(1:10))
# B: Center the labels
colLegend(x=1, y=9, height=6, col=colorRampPalette(c("blue", "white", "red"),
space = "rgb")(5), labels=list(1:5, adj = "center"))
# C: Outer frame
colLegend(x=3, y=9, height=6, col=colorRampPalette(c("blue", "white", "red"),
space = "rgb")(5), labels=1:4, box=list(border="grey", lty="dashed"))
# D
colLegend(x=5, y=9, height=6, col=colorRampPalette(c("blue", "white", "red"),
space = "rgb")(10), labels=sprintf("%.1f",seq(0,1,0.1)), cex=0.8)
# E: horizontal shape
colLegend(x=1, y=2, width=6, height=0.2, col=rainbow(500), labels=1:5,horiz=TRUE)
# F
colLegend(x=1, y=14, width=6, height=0.5, col=colorRampPalette(
c("black","blue","green","yellow","red"), space = "rgb")(100),
horiz=TRUE, box = TRUE)
# G
colLegend(x=1, y=12, width=6, height=1, col=colorRampPalette(c("black","blue",
"green","yellow","red"), space = "rgb")(10), horiz=TRUE,
border="black", title=list("From black to red", adj=0))
text(x = c(8,0.5,2.5,4.5,0.5,0.5,0.5)+.2, y=c(14,9,9,9,2,14,12), LETTERS[1:7], cex=2)
Convert R Colors to Hexadecimal Colors
Description
Convert any valid R color specification to hexadecimal colors.
Usage
colToHex(col, opacity = 1)
Arguments
col |
vector of valid R colors. |
opacity |
opacity value between 0 and 1. |
Value
Character vector of hexadecimal colors.
See Also
Examples
colToHex(c("tomato", "royalblue"))
colToHex("tomato", opacity = 0.5)
# color numbers refer to the current palette
colToHex(1:3)
Convert R Colors to HSV
Description
Convert any valid R color specification to HSV.
Usage
colToHsv(col, useAlphaChannel = FALSE)
Arguments
col |
vector of valid R colors. |
useAlphaChannel |
logical indicating whether the alpha channel should be included. |
Value
Numeric HSV matrix with one column per color. With
useAlphaChannel = TRUE the alpha channel is added as fourth row,
scaled to the range from 0 to 1 like the other rows.
See Also
Examples
colToHsv(c("tomato", "royalblue"))
# the alpha channel is added as fourth row, on a scale from 0 to 1
colToHsv("#FF634780", useAlphaChannel = TRUE)
Equivalent Opaque Color for Transparent Color
Description
Determine the equivalent opaque RGB color for a given partially transparent RGB color against a background of any color.
Usage
colToOpaque(col, opacity = NULL, bg = NULL)
Arguments
col |
the color as hex value (use converters below if it's not
available). |
opacity |
the opacity value, if left to NULL the alpha channels of the colors are used |
bg |
the background color to be used to calculate against (default is "white") |
Details
Reducing the opacity against a white background is a good way to find usable lighter and less saturated tints of a base color. For doing so, we sometimes need to get the equivalent opaque color for the transparent color.
Value
An named vector with the hexcodes of the opaque colors.
See Also
Other color.manipulation:
addOpacity(),
darken(),
fade(),
lighten(),
mixCol()
Examples
cols <- c(addOpacity("limegreen", 0.4),
colToOpaque(colToHex("limegreen"), 0.4),
"limegreen")
barplot(c(1, 1.2, 1.3), col=cols, panel.first=abline(h=0.4, lwd=10, col="grey35"))
Convert R Colors to RGB
Description
Convert any valid R color specification to an RGB matrix.
Usage
colToRgb(col, useAlphaChannel = FALSE)
Arguments
col |
vector of valid R colors. |
useAlphaChannel |
logical indicating whether the alpha channel should be included. |
Value
Integer matrix with rows corresponding to RGB (and optionally alpha) channels.
See Also
grDevices::col2rgb, color-conversion-overview
Examples
rgbToCol(matrix(c(162,42,42), nrow=3))
rgbToLong(matrix(c(162,42,42), nrow=3))
colToRgb("peachpuff")
colToRgb(c(blu = "royalblue", reddish = "tomato")) # names kept
colToRgb(1:8)
Color Conversion Functions in pharos
Description
pharos provides a family of functions for converting colors between
representations. Read each matrix as row -> column: the cell at
row X, column Y is the function that converts a color from
representation X to representation Y. - marks the diagonal
(no self-conversion), . marks a combination with no direct
function. RGB is the hub between the two tables below.
R color, hex, HSV, and RGB
| From \ To | Col | Hex | HSV | RGB |
| Col | - | colToHex() | colToHsv() | colToRgb() |
| Hex | hexToCol() | - | . | hexToRgb() |
| HSV | . | . | - | . |
| RGB | rgbToCol() | rgbToHex() | . | - |
"Col" is any valid R color specification (name, hex string, or
palette index) as accepted by grDevices::col2rgb().
No function starts from HSV: it is only ever a conversion target
(via colToHsv()), not a source – see the note below the
second table for the reason this gap is left open.
RGB, CMY, CMYK, and long integer
| From \ To | CMY | CMYK | Long | RGB |
| CMY | - | cmyToCmyk() | . | . |
| CMYK | cmykToCmy() | - | . | cmykToRgb() |
| Long | . | . | - | longToRgb() |
| RGB | rgbToCmy() | . | rgbToLong() | - |
Not part of either conversion matrix
Two related functions transform a color without changing its representation, so they don't fit a row/column slot above:
| Function | Purpose |
colToOpaque() | Computes the equivalent opaque color for a transparent color against a background -- Hex stays Hex |
grayScale() | Converts colors to grayscale using luminance weighting -- Col stays Col |
Why HSV has no source functions
Base R already provides the HSV -> Col/Hex direction via
grDevices::hsv(), which builds a hex color string
directly from h/s/v values – the same role rgb()
plays for RGB triplets. pharos deliberately doesn't duplicate it;
chain hsv() into colToRgb() or
colToHex() instead (see examples).
See Also
grDevices::col2rgb(), grDevices::hsv()
Examples
# A "." in the matrix means chaining two functions through a hub
# (usually RGB or Col), not a missing feature.
# CMY -> RGB: no direct function: CMY -> CMYK -> RGB
c(0.2, 0.6, 0.9) |> cmyToCmyk() |> cmykToRgb()
# Long integer -> R color name: Long -> RGB -> Col
255 |> longToRgb() |> rgbToCol()
# HSV -> RGB: base R's hsv() bridges the gap noted above
hsv(h = 0.6, s = 0.8, v = 0.9) |> colToRgb()
Choose Optimal Text Color Based on WCAG Contrast
Description
Computes the optimal text color (default: black or white) for a given background color based on the WCAG contrast ratio.
Usage
contrastCol(col, light = "white", dark = "black")
Arguments
col |
vector of colors. Can be any valid R color specification:
color names, hexadecimal strings (e.g. |
light |
color used for dark backgrounds (default: |
dark |
color used for light backgrounds (default: |
Details
This function implements the official relative luminance definition for sRGB colors (including gamma correction) and selects the text color that maximizes the contrast ratio according to the Web Content Accessibility Guidelines (WCAG 2.1).
Compared to simple heuristics (e.g., mean RGB), this approach is perceptually more accurate and suitable for accessibility-critical applications.
The relative luminance is computed as:
L = 0.2126 R + 0.7152 G + 0.0722 B
where R, G, B are linearized sRGB components:
c_{lin} =
\begin{cases}
\frac{c}{12.92} & c \le 0.04045 \\
\left(\frac{c + 0.055}{1.055}\right)^{2.4} & c > 0.04045
\end{cases}
The contrast ratio between two luminance values L1 and L2 is:
\frac{\max(L1, L2) + 0.05}{\min(L1, L2) + 0.05}
The function compares contrast ratios against light and dark and
returns the better option.
Value
A character vector of the same length as col, containing either
light or dark, depending on which yields the higher contrast ratio.
See Also
Other color.lookup:
findCol()
Examples
cols <- c("black", "white", "red", "blue", "yellow", "#777777")
contrastCol(cols)
# custom text colors
contrastCol(cols, light = "#FFFFFF", dark = "#222222")
Symbolic Unit Conversion Engine
Description
Converts numeric values between units using a symbolic unit system, SI-derived expansions, and graph-based conversion for non-SI units.
Usage
convUnit(x, from, to, prefix = NULL, units = NULL)
Arguments
x |
numeric value(s) to convert. |
from |
character string specifying the source unit. |
to |
character string specifying the target unit. |
prefix |
data frame of SI prefixes with columns
|
units |
data frame of unit conversion factors with columns
|
Details
Supports:
SI base units (m, kg, s, A, K, mol, cd)
Derived units (N, Pa, J, W, Hz)
Prefixes (k, m, µ, etc.)
Compound units (e.g.
"km/h","kg*m/s^2")Unit powers (e.g.
"m2","s^-1")Temperature conversion (C, F, K)
The function internally:
Parses units into symbolic components
Expands derived units (e.g.
N = kg*m/s^2)Computes dimensional vectors
Applies prefix scaling
Uses a graph search (Dijkstra) for non-SI conversions
The function checks dimensional consistency before conversion. If units are not compatible, an error is thrown.
For non-SI units (e.g. "mi", "bar"), conversion
paths are resolved via a graph representation of Units.
Temperature conversions are handled separately and do not use multiplicative scaling.
Value
Numeric value(s) converted to the target unit.
See Also
Other format:
fm(),
fmCI(),
print.Unit(),
style(),
unit()
Examples
convUnit(100, "km/h", "m/s")
convUnit(1, "N", "kg*m/s^2")
convUnit(1, "Pa", "N/m^2")
convUnit(25, "C", "F")
convUnit(1, "ml", "l")
Coordinate Transformations Cartesian/Polar/Spherical
Description
Transform cartesian into polar coordinates, resp. to spherical coordinates and vice versa.
Usage
polToCart(r, theta)
cartToPol(x, y)
cartToSph(x, y, z, up = TRUE)
sphToCart(r, theta, phi, up = TRUE)
Arguments
r |
a vector with the radius of the points. |
theta |
a vector with the angle(s) of the points. |
x, y, z |
vectors with the xy-coordianates to be transformed. |
up |
logical. If set to |
phi |
a vector with the angle(s) of the points. |
Details
Angles are in radians, not degrees (i.e., a right angle is pi/2). Use
degToRad() to convert, if you don't wanna do it by yourself.
All parameters are recycled if necessary.
Value
polToCart() returns a list of x and y coordinates of the points.
cartToPol() returns a list of r for the radius and theta for the angles of the
given points.
Note
Based on code by Christian W. Hoffmann
See Also
Other geometry.conversion:
degree-radians-conversion
Examples
cartToPol(x=1, y=1)
cartToPol(x=c(1,2,3), y=c(1,1,1))
cartToPol(x=c(1,2,3), y=1)
polToCart(r=1, theta=pi/2)
polToCart(r=c(1,2,3), theta=pi/2)
polToCart(r=c(1,2,3), theta=pi/2)
cartToSph(x=1, y=2, z=3) # r=3.741657, theta=0.930274, phi=1.107149
Darken Colors
Description
Darken colors by mixing them with black.
Usage
darken(col, amount = 0.2)
Arguments
col |
vector of valid R colors. |
amount |
numeric value between 0 and 1 specifying the amount of darkening. A value of 0 leaves the color unchanged, while 1 returns black. |
Details
Colors are mixed linearly with black in RGB space:
x_{new} = x \cdot (1 - amount)
Value
Character vector of hexadecimal colors.
See Also
Other color.manipulation:
addOpacity(),
colToOpaque(),
fade(),
lighten(),
mixCol()
Examples
darken("tomato")
darken(c("tomato", "royalblue"), amount = 0.5)
# increasing amounts
amount <- seq(0, 1, 0.2)
barplot(rep(1, 6), col = sapply(amount, darken, col = "tomato"),
names.arg = amount, yaxt = "n", xlab = "amount")
Convert Degrees to Radians and Vice Versa
Description
Convert degrees to radians (and back again).
Usage
degToRad(deg)
radToDeg(rad)
Arguments
deg |
a vector of angles in degrees. |
rad |
a vector of angles in radians. |
Value
degToRad returns a vector of the same length as deg with the
angles in radians.
radToDeg returns a vector of the same length as
rad with the angles in degrees.
See Also
Other geometry.conversion:
coordinate-conversions
Examples
degToRad(c(90,180,270))
radToDeg( c(0.5,1,2) * pi)
Ellipse Geometry
Description
Create an elliptic geometry.
Usage
ellipse(x = 0, y = 0, radiusX = 1, radiusY = radiusX, nPoints = 100)
Arguments
x, y |
centre coordinates. |
radiusX, radiusY |
horizontal and vertical radius. |
nPoints |
number of points used to approximate the ellipse. |
Details
Use rotate() to rotate the resulting geometry.
Value
An object inheriting from class "ellipseGeometry".
See Also
Other geometry.structures:
arc(),
band(),
bezier(),
circle(),
polygonX(),
regPolygon(),
ring()
Examples
canvas(xlim = c(-2, 2))
e <- ellipse(radiusX = 1.8, radiusY = 0.8)
polygonX(e, col = "lightblue")
# the same ellipse, rotated by 45 degrees
polygonX(rotate(e, theta = pi/4), border = "red")
Base64-encode a file
Description
The building block behind asImg() and
asFileLink(): reads a file and returns its contents
base64-encoded, ready to be placed in a data URI or in any container
format that carries binary payloads as text.
Usage
embedFile(path)
Arguments
path |
path to an existing file |
Value
a single character string
See Also
Other html:
asFileLink(),
asHtml(),
asImg(),
escapeHtml(),
htmlNotation,
htmlSubscript,
preview(),
preview.html(),
toHtmlTable()
Examples
fn <- tempfile(fileext = ".txt")
writeLines("hello", fn)
substr(embedFile(fn), 1, 8)
unlink(fn)
Add Error Bars to an Existing Plot
Description
Add vertical or horizontal error bars to an existing plot.
Usage
errBars(from, to = NULL, pos = NULL, horiz = TRUE, points = NULL, ...)
Arguments
from |
coordinates of the lower end of the error bars. If
|
to |
coordinates of the upper end of the error bars. |
pos |
position of the error bars. For vertical bars this corresponds to x-positions; for horizontal bars to y-positions. |
horiz |
logical; if |
points |
optional point specification. |
... |
additional graphical arguments passed to
|
Details
This is a lightweight wrapper around arrows() with
optional point symbols added via points().
Additional graphical arguments in ... are passed to
arrows() and may be used to control the appearance
of the error bars.
Common examples include:
-
col: line color -
lwd: line width -
lty: line type -
code: which end caps to draw -
length: length of the end caps
Point symbols may optionally be added:
-
points = TRUE: draw default points halfway betweenfromandto -
points = numeric: use these values as point coordinates -
points = list(...): fully specify point coordinates and graphical parameters
Example:
points = list( val = estimate, pch = 21, bg = "gold", col = "black", cex = 1.2 )
The default orientation is horizontal (horiz = TRUE), which
suits the typical use case of adding confidence intervals to a
dotchart(). Set horiz = FALSE for vertical bars
on barplots or similar.
Value
Invisibly returns a list with components:
- from
Lower endpoints
- to
Upper endpoints
- pos
Positions of the error bars
- points
Point coordinates
See Also
Other graphics.annotation:
barText(),
boxedText(),
colLegend(),
stamp(),
textLegend(),
titleRect()
Examples
op <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
b <- barplot(1:5, ylim = c(0, 6))
errBars(
from = 1:5 - 0.5,
to = 1:5 + 0.5,
pos = b,
length = 0.15
)
# midpoint symbols
b <- barplot(1:5, ylim = c(0, 6))
errBars(
from = 1:5 - 0.5,
to = 1:5 + 0.5,
pos = b,
points = TRUE
)
# custom points
dotchart(1:5, xlim = c(0, 6))
errBars(
from = 1:5 - 0.2,
to = 1:5 + 0.2,
horiz = TRUE,
points = list(
val = 1:5,
pch = 21,
bg = "gold",
col = "black",
cex = 1.2
)
)
par(op)
Escape HTML special characters
Description
Replaces the three characters that would otherwise be read as markup. Use it on any text of unknown origin – a variable label, a file name, a user-supplied caption – before pasting it into HTML or XML.
Usage
escapeHtml(x, attribute = FALSE)
Arguments
x |
a character vector |
attribute |
logical; also escape single and double quotes |
Details
Quotes are escaped as well when attribute = TRUE, which is
required for text placed inside an attribute value rather than between
tags.
Value
a character vector of the same length
See Also
Other html:
asFileLink(),
asHtml(),
asImg(),
embedFile(),
htmlNotation,
htmlSubscript,
preview(),
preview.html(),
toHtmlTable()
Examples
escapeHtml("Anteil < 5% & steigend")
escapeHtml('say "hi"', attribute = TRUE)
Export a Plot to Graphics Files
Description
Draws a plot to one or several graphics files (PNG, TIFF, PDF, SVG) in a
single call, controlled by a session-wide switch. It is meant for analysis
scripts that produce publication figures: the plot call is written once,
piped into exportPlot(), and the files are only (re)written when the
switch is on. Running a chunk interactively then shows the plot on screen
without overwriting the figures produced by an earlier, final run.
options(pharos.exportPlot = TRUE) # once, at the top of the script
plotXY(y ~ x, data = d) |>
exportPlot("fig1", type = c("png", "tif"))
Usage
exportPlot(
expr,
file,
type = "png",
width = 16/3,
height = width,
res = 300,
create = getOption("pharos.exportPlot", FALSE),
screen = TRUE
)
Arguments
expr |
a call that draws a plot, typically piped in with |
file |
the path of the output file, without extension; one file per
element of |
type |
one or several of |
width, height |
the size of the plot in inches. The default width of
|
res |
the resolution in dpi for the bitmap formats PNG and TIFF. Ignored for PDF and SVG. |
create |
logical; if |
screen |
logical; if |
Details
exportPlot() does not receive a finished plot but the plot call. The
native pipe rewrites f(x) |> exportPlot() into exportPlot(f(x)), and
since R evaluates arguments lazily, f(x) has not been run when
exportPlot() starts. The call is captured with substitute() and
evaluated once per output file on a freshly opened device, and finally
once on the current device. Every file is therefore drawn at its own size
and resolution: margins, label widths and font sizes that a plot function
computes from the device (e.g. via strwidth()) are right for each
format. Replaying a recorded plot (recordPlot()) would freeze the values
computed on the screen device instead.
This only works with the native pipe |> or with a direct call
exportPlot(plot(...), ...), which also accepts a braced block of several
drawing calls (see Examples). The magrittr pipe %>% hands over a
placeholder, not the call.
Repeated evaluation. Everything in expr runs once per output file
and once more on the screen if requested (screen): assignments,
messages, file operations and
expensive computations included. Prepare the data beforehand and pass
only the drawing calls.
Random numbers. If a random number generator state exists, it is
restored before each evaluation, so every output starts from the same
state, and the state after the call is that of a single evaluation. A plot
that draws random numbers (jitter, sampling) then comes out the same in
every file, as long as it consumes the same random numbers on every
device; a plot that branches on device properties may not. In a fresh
session in which no random number has been drawn yet there is no state to
restore, and the outputs are not synchronised; call set.seed() first.
Graphics systems. Base graphics are drawn by the call itself.
ggplot and trellis objects, which are only drawn when printed, are
printed on each device; a grob is drawn on a new page with
grid::grid.draw(). This applies only to a visible result, as at the
console: exportPlot(p, ...) draws the ggplot p, while
exportPlot(print(p), ...) draws it once through print(), which
returns it invisibly. An object returned invisibly is never drawn
automatically.
Switch. create defaults to the option pharos.exportPlot, which
is FALSE unless set. A script thus decides in one place whether its
figures are written, while single calls can still override it.
Devices. Each file device is closed by its own number after drawing,
also if the plot call fails or opens or activates another device. The
device that was current before the call is made current again, provided
it is still open. If a file device cannot be opened, exportPlot()
stops before drawing, with the device's own message as the reason; the
current device is left untouched, and files of earlier types in type
remain written.
Value
the paths of the written files as a character vector, invisibly;
character(0) if create = FALSE.
See Also
stamp() for the corner stamp, which plot functions in pharos
draw by default and which is usually suppressed (stamp = FALSE) in
figures for publication.
Examples
# without the switch, the plot is only drawn
plot(1:10) |>
exportPlot(file.path(tempdir(), "demo"))
# write a PNG and a PDF, nothing on the screen
f <- plot(1:10, main = "Demo") |>
exportPlot(file.path(tempdir(), "demo"), type = c("png", "pdf"),
width = 4, create = TRUE, screen = FALSE)
f
file.exists(f)
unlink(f)
# a composed base plot: the model is fitted outside, as expr is
# evaluated once per file
fit <- lm(dist ~ speed, data = cars)
f <- exportPlot({
plot(dist ~ speed, data = cars)
abline(fit)
legend("topleft", legend = "Regression", lty = 1)
}, file.path(tempdir(), "figure1"), create = TRUE, screen = FALSE)
unlink(f)
# switch it on for the whole script
opt <- options(pharos.exportPlot = TRUE)
f <- plot(1:10) |>
exportPlot(file.path(tempdir(), "demo"), screen = FALSE)
unlink(f)
options(opt)
Fade Colors
Description
Apply transparency and remove the alpha channel afterwards.
Usage
fade(col, opacity = 0.5)
Arguments
col |
vector of valid R colors |
opacity |
opacity value between 0 and 1 |
Value
Character vector of colors.
See Also
Other color.manipulation:
addOpacity(),
colToOpaque(),
darken(),
lighten(),
mixCol()
Examples
fade("tomato")
fade(c("tomato", "royalblue"), opacity = 0.2)
# same tint, but the faded color hides what lies behind it
cols <- c(addOpacity("tomato", 0.4), fade("tomato", 0.4))
barplot(c(1, 1), col = cols,
panel.first = abline(h = 0.5, lwd = 10, col = "grey35"))
Get Color on a Defined Color Range
Description
Find a color on a defined color range depending on the value of x. This is helpful for colorcoding numeric values.
Usage
findCol(
x,
col = rev(heat.colors(100)),
minX = NULL,
maxX = NULL,
all.inside = FALSE
)
Arguments
x |
numeric. |
col |
a vector of colors. |
minX |
the x-value to be used for the left edge of the first color. If
left to the default |
maxX |
the x-value to be used for the right edge of the last color. If
left to the default |
all.inside |
logical; if true, the returned indices are coerced into
|
Details
For the selection of colors the option rightmost.closed in the used
function findInterval() is set to TRUE. This will ensure that
all values on the right edge of the range are assigned a color. How values
outside the boundaries of minX and maxX should be handled can be
controlled by all.inside. Set this value to TRUE, if those values
should get the colors at the edges or set it to FALSE, if they should remain
white (which is the default).
Note that findInterval() closes the intervals on the left side,
e.g. [0, 1). This option can't be changed. Consequently will x-values lying
on the edge of two colors get the color of the bigger one.
Value
A vector of the length of x with the colors assigned to the
values, taken from col (names of col are kept). Values outside the
range minX to maxX yield NA, unless all.inside is TRUE.
See Also
Other color.lookup:
contrastCol()
Examples
canvas(7, main="Use of function findCol()")
# get some data
x <- c(23, 56, 96)
# get a color range from blue via white to red
cols <- colorRampPalette(c("blue","white","red"))(100)
colLegend(x="bottomleft", col=cols, labels=seq(0, 100, 10), cex=0.8)
# and now the color coding of x:
(xcols <- findCol(x, cols, minX=0, maxX=100))
# this should be the same as
cols[x+1]
# how does it look like?
y0 <- c(-5, -2, 1)
text(x=1, y=max(y0)+2, labels="Color coding of x:")
text(x=1.5, y=y0, labels=x)
polygonX(regPolygon(x=3, y=y0, nVertices=4, startAngle=pi/4), col=xcols)
text(x=6, y=y0, labels=xcols)
# how does the function select colors?
canvas(xlim = c(0,1), ylim = c(0,1))
cols <- c(red="red", yellow="yellow", green="green", blue="blue")
colLegend(x=0, y=1, width=1, col=rev(cols), horiz = TRUE,
labels=format(seq(0, 1, .25), digits=2, nsmall=2),
box=list(border="grey"), cex=0.8 )
x <- c(-0.2, 0, 0.15, 0.55, .75, 1, 1.3)
arrows(x0 = x, y0 = 0.6, y1 = 0.8, angle = 15, length = .2)
text(x=x, y = 0.5, labels = x, adj = c(0.5,0.5))
text(x=x, y = 0.4, labels = names(findCol(x, col=cols,
minX = 0, maxX = 1, all.inside = TRUE)), adj = c(0.5,0.5))
text(x=x, y = 0.3, labels = names(findCol(x, col=cols,
minX = 0, maxX = 1, all.inside = FALSE)), adj = c(0.5,0.5))
Format Numbers and Dates
Description
Formatting numbers with base R tools often degenerates into a major
intellectual challenge for us little minds down here in the valley of tears.
There are a number of options available and quite often it's hard to work
out which one to use, when a more uncommon setting is needed. The
fm() function wraps all these functions and tries to offer a simpler,
less technical, but still flexible interface.
Usage
fm(
x,
digits = NULL,
leadDigits = NULL,
sci = NULL,
bigMark = NULL,
decMark = NULL,
naForm = NULL,
zeroForm = NULL,
fmt = NULL,
pThreshold = NULL,
width = NULL,
align = NULL,
lang = NULL,
...
)
## Default S3 method:
fm(
x,
digits = NULL,
leadDigits = NULL,
sci = NULL,
bigMark = NULL,
decMark = NULL,
naForm = NULL,
zeroForm = NULL,
fmt = NULL,
pThreshold = NULL,
width = NULL,
align = NULL,
lang = NULL,
...
)
## S3 method for class 'data.frame'
fm(
x,
digits = NULL,
leadDigits = NULL,
sci = NULL,
bigMark = NULL,
decMark = NULL,
naForm = NULL,
zeroForm = NULL,
fmt = NULL,
pThreshold = NULL,
width = NULL,
align = NULL,
lang = NULL,
...
)
## S3 method for class 'matrix'
fm(
x,
digits = NULL,
leadDigits = NULL,
sci = NULL,
bigMark = NULL,
decMark = NULL,
naForm = NULL,
zeroForm = NULL,
fmt = NULL,
pThreshold = NULL,
width = NULL,
align = NULL,
lang = NULL,
...
)
## S3 method for class 'table'
fm(
x,
digits = NULL,
leadDigits = NULL,
sci = NULL,
bigMark = NULL,
decMark = NULL,
naForm = NULL,
zeroForm = NULL,
fmt = NULL,
pThreshold = NULL,
width = NULL,
align = NULL,
lang = NULL,
...
)
## S3 method for class 'ftable'
fm(
x,
digits = NULL,
leadDigits = NULL,
sci = NULL,
bigMark = NULL,
decMark = NULL,
naForm = NULL,
zeroForm = NULL,
fmt = NULL,
pThreshold = NULL,
width = NULL,
align = NULL,
lang = NULL,
...
)
Arguments
x |
a numeric, logical, character, factor, |
digits |
integer, the desired (fixed) number of digits after the
decimal point. You will always get this number of digits, even if the last
digit is 0. In scientific notation it is the number of decimals of the
mantissa. Negative numbers of digits round to
a power of ten ( |
leadDigits |
number of leading zeros. |
sci |
numeric scalar giving the absolute power-of-ten threshold for
scientific notation. It applies to the absolute value of |
bigMark |
character; if not empty used as mark between every 3
digits before the decimal point. If |
decMark |
character specifying the decimal mark. If |
naForm |
character, string specifying how |
zeroForm |
character, string specifying how zeros should be specially
formatted. Useful for pretty printing 'sparse' objects. If set to
|
fmt |
a format code or date-time template, a formatting function, a
named Style, or an object of class |
pThreshold |
positive numeric threshold below which p-values are shown
as |
width |
nonnegative integer giving the minimum display width |
align |
the character on whose position the strings will be aligned.
Left alignment can be requested by setting |
lang |
optional value setting the language for the months and daynames.
Can be either |
... |
additional arguments passed to methods or to a formatting
function supplied through |
Details
There's also an easygoing interface for format templates, defined as a list consisting of any accepted format features. This enables to define templates globally and easily change or modify them later.
fm() is the workhorse for formatting numbers and dates, supporting a
comprehensive range of format options that are likely to occur in everyday
reporting. Among these, the argument fmt deserves a more detailed
description due to its flexibility. It is used to generate a variety of
different special formats.
If x is a date, it can take
ISO-8601-inspired token syntax similar to .NET or Moment.js (consisting of
d, M and y for day, month or year and h/H,
m, s, t for hours, minutes, seconds and AM/PM
designator) and defining the combination of day month and year
representation.
Code | Description |
d | day of the month without leading zero (1 - 31) |
dd | day of the month with leading zero (01 - 31) |
ddd | abbreviated name for the day of the week (e.g. Mon) in the current user's language |
dddd | full name for the day of the week (e.g. Monday) in the current user's language |
do | The token do (aka 'day
ordinal') formats the day of month using English ordinal suffixes (e.g. 1st,
2nd, 3rd, 4th). This is an English-only feature. (For most other languages,
ordinal dates are written using punctuation in the format string, e.g.
"d. MMM yyyy". Locale-specific ordinal rules beyond English are not
implemented by design.) |
M | month without leading zero (1 - 12) |
MM | month with leading zero (01 - 12) |
MMM
| abbreviated month name (e.g. Jan) in the current user's language |
MMMM | full month name (e.g. January) in the current user's language |
y | year without century, without leading zero (0 - 99) |
yy | year without century, with leading zero (00 - 99) |
yyyy | year with century. For example: 2005 |
H/HH | Hour in 24h format, one digit / two digits |
h/hh | Hour in 12h format, one digit / two digits, note that in this case t must be set also to ensure uniqueness. |
t/tt | AM/PM description (one/two characters) |
m/mm | Minutes one digit / two digits |
s/ss | Seconds one digit / two digits |
Weekdays and month names can be expressed in the local language or in
English. The language can be controlled by the argument "lang".
Even more variability is needed to display numeric values. For the most frequently used formats there are the following special codes available:
| Code | Type | Description |
e | scientific | forces scientific representation of x, e.g.
3.141e-05. digits gives the number of |
| decimals of the mantissa; alignment and zero values are further respected. | ||
eng | engineering | forces scientific representation of
x, but only with powers that are a multiple of 3. |
engabb | engineering abbr. | same as
eng, but replaces the exponential representation by codes, |
e.g. M for mega (1e6). |
||
\% | percent | multiplies the given number by 100 and appends the \ formats values as p-values. |
Use pThreshold to define
the threshold to e.g.
switch to a <0.001 representation. |
||
frac | fractions | will (try to) convert numbers to fractions. So 0.1 will be displayed as 1/10. |
See MASS::fractions(). |
||
* | significance | will produce a significance representation of a p-value consisting of * and ., |
while the breaks are set
according to the used defaults e.g. in lm as |
||
[0, 0.001]
= *** |
||
(0.001, 0.01] = ** |
||
(0.01,
0.05] = * |
||
(0.05, 0.1] = . |
||
(0.1,1]
= |
||
p* | p-value stars | will produce p-value and significance stars |
fmt can as well be an object of class "Style" consisting of a
list out of the arguments above (as created by style()). This
allows to store and manage the full format in variables or as options and
use it as format template subsequently. Arguments supplied directly to
fm() override the corresponding Style settings. NULL means
"not specified" and therefore leaves the Style setting in place.
For data frames and ftables, every formatting argument must have length one or the number of columns. Length-one arguments are recycled, allowing each column to use its own formatting settings without ambiguous partial recycling. Functions and Style objects count as single settings; use a list to supply different functions or Styles by column.
Finally, fmt can be a function of x. Additional arguments in
\dots are forwarded to that function.
Value
formatted character values with the dimensions or tabular structure
of x preserved where applicable, of class noquote so that
they print without quotation marks. Every value is formatted on its own,
whatever the shape of x: a matrix or a table is formatted exactly like
the vector of its entries and is not padded to a common width. Padding
is applied only on request, via width or align. To display a
formatted matrix with its entries lined up, print it right justified,
e.g. print(fm(m), right = TRUE), or align it explicitly.
See Also
base::format, base::formatC,
base::prettyNum, base::sprintf, stats::symnum,
base::Sys.setlocale,
DescToolsX::weekday,
DescToolsX::month,
theme
Other format:
convUnit(),
fmCI(),
print.Unit(),
style(),
unit()
Examples
# mind the case: M is the month, m the minutes
fm(as.Date(c("2014-11-28", "2014-1-2")), fmt="ddd, d MMMM yyyy")
fm(as.Date(c("2014-11-28", "2014-1-2")), fmt="ddd, d MMMM yyyy", lang="local")
# using english ordinal suffixes
fm(as.Date("2026-01-21"), fmt="MMMM do yyyy", lang="en")
# e.g. in context:
gettextf("Report generated on %s",
fm(as.Date("2026-05-04"), fmt="MMMM do, yyyy", lang="en"))
# numeric formats
x <- pi * 10^(-10:10)
fm(x, digits=3, fmt="%")
fm(x, digits=4, sci=4, leadDigits=0, width=9, align=".")
# format a matrix: every entry on its own, as for a vector ...
m <- matrix(runif(100) - 0.5, nrow=10,
dimnames=list(LETTERS[1:10], LETTERS[1:10]))
fm(m, digits=1)
# ... lined up for display only when asked for
print(fm(m, digits=1), right = TRUE)
fm(m, digits=1, align=".")
# engineering format
fm(x, fmt="eng", digits=2)
fm(x, fmt="engabb", leadDigits=2, digits=2)
# combine with grams [g]
paste(fm(x, fmt="engabb", leadDigits=2, digits=2), "g", sep="")
# example form symnum
pval <- rev(sort(c(outer(1:6, 10^-(1:3)))))
noquote(cbind(fm(pval, fmt="p"), fm(pval, fmt="*")))
# change the character to be used as the decimal point
fm(1200, digits=2, bigMark = ".", decMark=",")
Format Confidence Intervals
Description
Format confidence intervals using a flexible template.
Usage
fmCI(x, template = NULL, ...)
Arguments
x |
the numerical values, given in the order in which they are used in the template. |
template |
character string as template for the desired format.
%s are the placeholders for the numerical values. Default
is |
... |
the dots are passed on to the |
Value
a formatted string
See Also
Other format:
convUnit(),
fm(),
print.Unit(),
style(),
unit()
Examples
x <- c(est=2.1, lci=1.5, uci=3.8)
# default template
fmCI(x)
# user defined template (note the double percent code)
fmCI(x, template="%s (95%%-CI %s-%s)", digits=1)
# in higher datastructures
tapply(warpbreaks$breaks, warpbreaks$wool,
function(x) fmCI(c(mean(x), t.test(x)$conf.int),
digits=1))
Flat Contingency Table for tapply-Like Lists
Description
Creates a flat contingency table from a list array, such as the result of
tapply() when the applied function returns a named vector.
Usage
## S3 method for class 'list'
ftable(x, row.vars = NULL, col.vars = NULL, ...)
Arguments
x |
A list with a |
row.vars |
row variables passed to |
col.vars |
column variables passed to |
... |
further arguments passed to |
Details
Each list element is expanded into an additional dimension corresponding to
the names of the returned vector. The resulting array is then passed to
ftable().
This is particularly useful for displaying multi-dimensional summaries such
as confidence intervals returned by meanCI(), where each cell contains
several statistics (e.g. estimate, lower CI, upper CI).
The names of the vectors stored in the list elements become an additional dimension of the resulting array. By default, this new dimension is shown in the columns of the flat contingency table.
Value
An object of class "ftable".
See Also
Examples
# a function returning a named vector, here the mean and its
# confidence interval (as e.g. lumen::meanCI() returns them)
meanCI <- function(z) {
ci <- t.test(z)$conf.int
c(est = mean(z), lci = ci[1], uci = ci[2])
}
x <- with(
warpbreaks,
tapply(
breaks,
list(wool, tension),
meanCI
)
)
# the statistics form the columns
ftable(x)
# the second grouping variable in the columns as well
ftable(
x,
row.vars = 2,
col.vars = c(3, 1)
)
Graphics Framework Helpers
Description
The internal machinery every plot function in the suite is built on:
state management, parameter resolution, title handling and the two
element dispatchers. They are exported so that plot functions living in
other packages of the suite - a plot.FitMod() in alloy, a
plot.Desc.* method anywhere outside pharos - can follow the same
contract instead of reimplementing it.
They are not part of the user-facing API. Nothing here is meant to be called from an analysis script, and the signatures may change with the framework.
| Helper | Purpose |
.withGraphicsState() | save/restore par(), draw the stamp on success |
.applyParFromDots() | apply graphical parameters from ... over defaults |
.resolveTitle() | three-state main contract (§9.4) |
.marTop() | top margin implied by the resolved title |
.marginLines() | left margin implied by the drawn tick labels |
.drawGrid() | grid dispatcher, understands .useTheme |
.drawBox() | box dispatcher, understands .useTheme |
.useTheme | sentinel telling "resolve against the active theme" (§9.3) |
Resolves a callIf-style grid spec against the current theme and, unless
suppressed, draws a grid via graphics::grid(). This is the single
choke point for grid rendering in all plot functions, guaranteeing
consistent precedence: function defaults < theme settings < user spec.
Counterpart to .drawGrid() for graphics::box(). Resolves a
callIf-style box spec against the current theme and draws the plot
box unless suppressed.
Runs expr (typically the body of a high-level plot function) while
guaranteeing that all commonly modified par() settings are restored
afterwards, and optionally places a stamp annotation and resets the
layout once the expression has completed successfully.
Central dispatcher that translates the three sources of graphical
parameters into par() calls, in strictly increasing precedence:
Returns the top margin in lines: compact (room for the axis only) when no title will be drawn, generous otherwise. Centralizes the two values as theme defaults instead of magic numbers at 40 call sites.
Normalizes the user-facing main argument: FALSE, "" and NA
mean "suppress the title" and map to "". NULL means "no title
unless asked for": the function's derived default is used only when
the theme sets autoTitle = TRUE, or when always = TRUE because the
title carries information that is shown nowhere else (the palette name
in plot.Palette(), the panel type in plot.Desc.*()).
Like .neededMargin(), but takes the label orientation (las) into
account: with perpendicular labels (las 2/3) the label width
governs the required space regardless of the axis side. Adds a 15%
safety factor to absorb rounding and font metric differences across
devices.
Usage
.useTheme
.drawGrid(grid, defaults = list())
.drawBox(box, defaults = list())
.withGraphicsState(expr, stamp = .useTheme, resetLayout = FALSE)
.applyParFromDots(..., exclude = "cex", defaults = list())
.marTop(main)
.resolveTitle(main, default = "", always = FALSE)
.marginLines(
labels,
side = 4,
las = par("las"),
cex = par("cex"),
pad = 0,
axisLine = 0
)
Arguments
grid |
a callIf-style spec: the sentinel |
defaults |
named list of function-level default parameters (tier 2). |
box |
a callIf-style spec: |
expr |
the plot expression, evaluated in the caller's frame via
|
stamp |
controls the stamp annotation drawn after a successful
plot: the sentinel |
resetLayout |
logical; if |
... |
user-supplied graphical parameters (the dots of the calling plot function). |
exclude |
character vector of parameter names that must never
reach |
main |
the |
default |
the function's derived title, used for |
always |
logical; use |
labels |
character vector of labels to accommodate; |
side |
integer, the axis side (1 = bottom, 2 = left, 3 = top, 4 = right). |
las |
label orientation as in |
cex |
character expansion used for measuring; defaults to
|
pad |
additional padding in lines. |
axisLine |
offset of the axis labels from the plot region, in lines. |
Details
Theme entries whose names start with "group." are stripped
before merging, as they parameterize grouped-plot variants and are not
valid graphics::grid() arguments.
This is the outermost wrapper of the shared plot setup path: every
plot*() function routes its drawing code through here, so state
restoration and stamping never have to be handled at individual call
sites.
Deliberately not saved/restored: oma/omi. Restoring these resets
the multi-figure state and thereby destroys user-defined mfrow/
layout() arrangements between panels (each par(omi = ...) call
restarts the page). Exception: with resetLayout = TRUE the calling
function has set up its own layout and thus owns the page; oma is
then restored after the layout reset.
Deliberately not saved/restored: oma/omi. Restoring these resets
the multi-figure state and thereby destroys user-defined mfrow/
layout() arrangements between panels (each par(omi = ...) call
restarts the page).
Warnings inside expr are raised immediately (warn = 1) so they
appear in the context of the failing plot call rather than being
deferred to the end of the top-level call.
The success flag ok ensures that neither the stamp nor the layout
reset fires when expr throws: a half-drawn plot is not stamped, and
the (possibly user-owned) layout is left untouched for inspection.
-
Theme
par(getTheme()$par) – global styling, lowest tier. -
Function defaults (
defaults), each individually overridable via the correspondingDescToolsX.plot.<name>option (see.resolvePar()). -
User dots (
...) – explicit arguments at the call site, highest tier.
Only names that are settable par() parameters are applied; anything
else in ... is silently ignored here (it is typically consumed by
the plot primitives instead).
mar and oma receive partial-update semantics: a named vector
(c(top = 6)) patches only the given sides (names must be from
bottom, left, top, right); an unnamed vector is recycled to
length 4, with NA entries keeping the current value
(mar = c(NA, 8, NA, NA) widens only the left margin).
Value
Invisibly NULL; called for its side effect (drawing).
Invisibly NULL; called for its side effect (drawing).
Invisibly NULL; called for its side effects.
Invisibly NULL; called for its side effect on par().
A single numeric: 2.1 (no title) or 4.1 (title present).
A character string: default, "", or main itself.
A single numeric: the required margin size in lines (ceiling).
Why these are exported
Section 9.7 of the design rules gives the unavailability of these
helpers outside pharos as the reason plot.Desc.* methods live in
pharos rather than next to the classes they plot. That reason no
longer holds. The placement of the existing methods is unchanged - the
export only removes the constraint, it does not itself relocate
anything.
Contract for callers outside pharos
The rules in sections 9.1-9.5 apply unchanged: no direct par() call
outside .applyParFromDots(), stamp passed to
.withGraphicsState() rather than drawn by hand, no oma/omi in any
save/restore list, and no internal mfrow.
Convert Colors to grayScale
Description
Convert colors to grayScale using luminance weighting.
Usage
grayScale(col)
Arguments
col |
vector of valid R colors. |
Details
grayScale conversion uses the standard luminance approximation:
0.3 R + 0.59 G + 0.11 B
Value
Character vector of grayScale colors.
See Also
Examples
op <- par(no.readonly = TRUE)
par(mfcol=c(2,2))
tmp <- 1:3
names(tmp) <- c('red','green','blue')
barplot(tmp, col=c('red','green','blue'))
barplot(tmp, col=grayScale(c('red','green','blue')))
barplot(tmp, col=c('red','#008100','#3636ff'))
barplot(tmp, col=grayScale(c('red','#008100','#3636ff')))
par(op)
Helsana Colors
Description
Retrieve one or more colors from the helsana palette, optionally faded.
Usage
hcol(..., fade = NULL)
Arguments
... |
character strings naming the colors to retrieve. Valid names are:
|
fade |
|
Value
A named character vector of hex color codes.
See Also
Other color.palettes:
pal(),
palNames()
Examples
hcol("blue", "green")
hcol()
# lighter tints, still opaque
hcol("blue", "red", fade = 0.4)
hcol("blue", fade = c(1, 0.6, 0.3))
Convert Hex Colors to Named R Colors
Description
Convert hexadecimal colors to the nearest named R colors.
Usage
hexToCol(col, method = c("ciede2000", "cie76"))
Arguments
col |
character vector of hexadecimal colors. |
method |
color difference formula, |
Value
Character vector of named R colors.
See Also
Examples
hexToCol(c("#A22A2A", "#4169E0"))
hexToCol("#4169E0", method = "cie76")
Convert Hex Colors to RGB
Description
Convert hexadecimal color strings to an RGB matrix.
Usage
hexToRgb(col)
Arguments
col |
character vector of hexadecimal colors. |
Value
Integer matrix with RGB rows.
See Also
Examples
hexToRgb(c("#A52A2A", "#FFDAB9"))
# an alpha channel is kept
hexToRgb("#A52A2A80")
HTML notation for hat and bar diacritics
Description
Append the HTML entity for a circumflex (“hat”, as in an
estimator \hat{x}) or macron (“bar”, as in a sample mean
\bar{x}) to a label.
Usage
htmlHat(x)
htmlBar(x)
Arguments
x |
a character vector, typically a variable name or symbol |
Value
a character vector with the diacritic's HTML entity appended
See Also
Other html:
asFileLink(),
asHtml(),
asImg(),
embedFile(),
escapeHtml(),
htmlSubscript,
preview(),
preview.html(),
toHtmlTable()
Examples
htmlHat("p") # -> "p̂" (renders as p with a circumflex)
htmlBar("x") # -> "x̄" (renders as x with a macron)
Subscript notation
Description
Infix operator producing an HTML subscript, e.g. for indexed symbols
such as x_i.
Usage
x %_% i
Arguments
x |
a character vector (the base symbol) |
i |
a character vector (the subscript), recycled against |
Value
a character vector: x followed by <sub>i</sub>
See Also
Other html:
asFileLink(),
asHtml(),
asImg(),
embedFile(),
escapeHtml(),
htmlNotation,
preview(),
preview.html(),
toHtmlTable()
Examples
"x" %_% "i" # -> "x<sub>i</sub>"
Check Whether the Current Plot Region Is Large Enough
Description
Tests whether the plot region of the active graphics device meets a
minimal size requirement. This is useful before drawing into small
devices or heavily subdivided layouts (mfrow, layout(),
Shiny render panes), where an undersized region would otherwise fail
with the rather cryptic error "figure margins too large".
Usage
isValidPlotRegion(minPin = .getOption("plot.minPin", c(0.5, 0.5)))
Arguments
minPin |
numeric vector of length 2, giving the minimal required
width and height of the plot region in inches. Defaults to the option
|
Details
The plot region is the area inside the figure margins, as reported by
par("pin"). Its size results from the device dimensions minus
the current margins (mar, oma), so both a small device
and oversized margins can render it degenerate.
If no graphics device is open (dev.cur() == 1), the function
returns TRUE, since the next high-level plot call will open a
fresh device with default dimensions. Note that querying par()
in this state would itself open a device as a side effect, which this
function deliberately avoids.
The function has no side effects and never throws; it is meant as a
guard for conditional plotting, e.g.
if (isValidPlotRegion()) plot(x) else message("device too small").
Value
a single logical: TRUE if the plot region is at least
minPin inches in both dimensions (or if no device is open),
FALSE otherwise.
See Also
par() (entries pin, fin, mar),
dev.cur()
Other graphics.layout:
abcCoords(),
axTicksPosixct(),
axisBreak(),
lineToUser(),
mar(),
plotFacet(),
spreadOut()
Examples
# guard a plot against a degenerate region
if (isValidPlotRegion()) {
plot(rnorm(20))
} else {
message("plot region too small")
}
# require a larger region, e.g. for a wide correlation plot
isValidPlotRegion(minPin = c(4, 3))
Lighten Colors
Description
Lighten colors by mixing them with white.
Usage
lighten(col, amount = 0.2)
Arguments
col |
vector of valid R colors. |
amount |
numeric value between 0 and 1 specifying the amount of lightening. A value of 0 leaves the color unchanged, while 1 returns white. |
Details
Colors are mixed linearly with white in RGB space:
x_{new} = x + amount \cdot (255 - x)
Value
Character vector of hexadecimal colors.
See Also
Other color.manipulation:
addOpacity(),
colToOpaque(),
darken(),
fade(),
mixCol()
Examples
lighten("tomato")
lighten(c("tomato", "royalblue"), amount = 0.5)
# increasing amounts
amount <- seq(0, 1, 0.2)
barplot(rep(1, 6), col = sapply(amount, lighten, col = "tomato"),
names.arg = amount, yaxt = "n", xlab = "amount")
Create a Line Separator String
Description
Generates a character string that can be used as a horizontal line separator in console output.
Usage
lineSep(sep = .getOption("linesep"))
Arguments
sep |
A character string used as separator. If |
Details
ANSI escape sequences (e.g., color codes) are removed using
cli::ansi_strip() when determining the visible width.
The console width is determined via getOption("width", 80).
Value
A character string representing a horizontal separator line.
Examples
lineSep()
lineSep("-")
lineSep(cli::col_red("="))
Convert Line Coordinates To User Coordinates
Description
Functions like mtext or axis use the line argument to
set the distance from plot. Sometimes it's useful to have the distance in
user coordinates. lineToUser() does this nontrivial conversion.
Usage
lineToUser(line, side)
Arguments
line |
the number of lines |
side |
the side of the plot |
Details
For the lineToUser function to work, there must be an open plot.
Value
the user coordinates for the given lines
See Also
Other graphics.layout:
abcCoords(),
axTicksPosixct(),
axisBreak(),
isValidPlotRegion(),
mar(),
plotFacet(),
spreadOut()
Examples
plot(1:10)
lineToUser(line=2, side=4)
Add a Linear Regression Line
Description
Add a linear regression line to an existing plot. The function first
calculates predictions from an lm object and then adds the fitted
line together with optional confidence and prediction bands.
Usage
## S3 method for class 'lm'
lines(
x,
col = pal()[1],
lwd = 2,
lty = "solid",
type = "l",
n = 100,
cband = list(conf.level = 0.95),
pband = NA,
xpred = NULL,
...
)
## S3 method for class 'lmlog'
lines(
x,
col = pal()[1],
lwd = 2,
lty = "solid",
type = "l",
n = 100,
cband = list(conf.level = 0.95),
pband = NA,
xpred = NULL,
...
)
Arguments
x |
linear model object as returned by |
col |
line color. Defaults to |
lwd |
line width. |
lty |
line type. |
type |
plotting type passed to |
n |
number of points used for plotting the fit. |
cband |
controls the confidence band. May be |
pband |
controls the prediction band, as |
xpred |
optional numeric vector defining the range over which predictions should be calculated. |
... |
further graphical parameters passed to |
Details
In contrast to abline(), polynomial models and transformed
predictors are supported as long as the model contains exactly one predictor
variable. A polynomial, y ~ poly(x, 2) or y ~ x + I(x^2), is drawn
against x; a single transformed term such as y ~ log(x) is drawn
against the transformed values, matching plot(y ~ log(x)).
Confidence and prediction bands are controlled via cband and
pband. These arguments can be:
-
FALSE,NULLorNA: suppress the band -
TRUE: draw the band with default settings a named list: customize the band appearance and confidence level
Value
No return value; called for its side effect.
See Also
Other graphics.trendlines:
lines.loess(),
splineCI
Examples
plot(dist ~ speed, cars)
lines(lm(dist ~ speed, cars))
# polynomial model with a 99% confidence band and a prediction band
plot(dist ~ speed, cars)
lines(lm(dist ~ poly(speed, 2), cars), col = "red",
cband = list(conf.level = 0.99), pband = TRUE)
# transformed predictor, no bands
plot(mpg ~ log(hp), mtcars)
lines(lm(mpg ~ log(hp), mtcars), cband = FALSE)
Add a Loess Smoother and Its Confidence Band
Description
Add a loess smoother to an existing plot. The function first calculates
predictions from a loess object and then adds the fitted smoother
together with an optional confidence band.
Usage
## S3 method for class 'loess'
lines(
x,
col = .useTheme,
lwd = 2,
lty = "solid",
type = "l",
n = 100,
band = list(conf.level = 0.95),
...
)
Arguments
x |
a fitted |
col |
line color of the smoother. |
lwd |
line width. |
lty |
line type. |
type |
plotting type passed to |
n |
number of points used for plotting the fit. |
band |
controls the confidence band. May be |
... |
further graphical parameters passed to |
Details
The confidence band is controlled via band. This argument may be:
-
FALSE,NULLorNA: suppress the band -
TRUE: draw the band with default settings a named list: customize the band appearance and confidence level
Value
No return value (invisible NULL), called for its side effect of
adding the smoother and its confidence band to the current plot.
Note
Loess can result in substantial computational load for large datasets.
See Also
loess(), scatter.smooth(),
smooth.spline()
Other graphics.trendlines:
lines.lm(),
splineCI
Examples
x <- runif(100)
y <- rnorm(100)
plot(x, y)
lines(loess(y ~ x))
plot(dist ~ speed, cars)
lines(
loess(dist ~ speed, cars),
band = list(
conf.level = 0.99,
col = addOpacity("red", 0.4),
border = "black"
)
)
Convert Long Integers to RGB
Description
Decode long integers into RGB values.
Usage
longToRgb(col)
Arguments
col |
integer vector. |
Value
RGB matrix.
See Also
Examples
longToRgb(c(255, 65280, 16711680))
# there and back again
rgbToHex(longToRgb(rgbToLong(colToRgb("tomato"))))
Get or set plot margins conveniently
Description
Convenience wrapper around graphics::par() for getting and setting
plot margins (mar) or outer margins (oma). Individual sides can
be modified without affecting the others.
Usage
mar(bottom = NULL, left = NULL, top = NULL, right = NULL, outer = FALSE)
Arguments
bottom, left, top, right |
numeric scalars specifying the margin size
(in lines) for each side. If |
outer |
logical; if |
Details
This function simplifies partial updates of par("mar") or par("oma").
It avoids the need to manually query and reconstruct the full margin vector.
For restoring graphical parameters, the recommended base R approach is:
op <- par(no.readonly = TRUE) on.exit(par(op))
Value
If no arguments are provided, returns the current margin vector (numeric of length 4). Otherwise, sets the margins and returns the new values invisibly.
See Also
Other graphics.layout:
abcCoords(),
axTicksPosixct(),
axisBreak(),
isValidPlotRegion(),
lineToUser(),
plotFacet(),
spreadOut()
Examples
# Get current margins
mar()
# Set bottom margin only
mar(bottom = 2)
# Set multiple margins
mar(bottom = 2, left = 2)
# Modify outer margins
mar(top = 1, outer = TRUE)
Mix Colors
Description
Mix two sets of colors in RGB space.
Usage
mixCol(col1, col2, weights = 0.5)
Arguments
col1 |
first vector of colors. |
col2 |
second vector of colors. |
weights |
numeric value between 0 and 1 specifying the
contribution of |
Details
Colors are mixed linearly in RGB space:
x_{mix} = (1 - weights) x_1 + weights x_2
All arguments are recycled as necessary.
Value
Character vector of hexadecimal colors.
See Also
Other color.manipulation:
addOpacity(),
colToOpaque(),
darken(),
fade(),
lighten()
Examples
mixCol("red", "blue")
mixCol("red", "blue", weights = 0.2)
# the shorter vector is recycled
mixCol(c("red", "yellow"), "blue")
# from red to blue
w <- seq(0, 1, 0.1)
barplot(rep(1, 11), col = sapply(w, mixCol, col1 = "red", col2 = "blue"),
names.arg = w, yaxt = "n", xlab = "weights")
Get a Color Palette
Description
Returns n colors from a named palette. All palettes always return
exactly n colors regardless of their base size:
-
n < length(base): evenly spaced sample for maximum contrast -
n = length(base): returned as-is -
n > length(base): interpolated viagrDevices::colorRampPalette()
Usage
pal(name, n = NA, opacity = 1)
## S3 method for class 'Palette'
plot(x, main = NULL, cex = 0.85, border = "grey70", stamp = .useTheme, ...)
Arguments
name |
character or integer. Palette name (full match via
|
n |
integer, number of colors to return. Default |
opacity |
numeric in |
x |
palette object to be plotted. |
main |
main title. |
cex |
character expansion of the labels (index, name, hex code). It is reduced automatically when the rows get too narrow, and the labels are left out for very long palettes. |
border |
color for the border of the swatches. |
stamp |
controls the corner stamp. |
... |
further graphical parameters, passed to |
Value
a character vector of n hex color codes of class
c("palette", "character") with a "name" attribute.
See Also
palNames(), grDevices::colorRampPalette(),
grDevices::adjustcolor()
Other color.palettes:
hcol(),
palNames()
Examples
# default palette from options
pal()
# discrete palette — 3 maximally contrasting colors
pal("dark", n = 3)
# continuous gradient — 50 colors
pal("red-white-blue-2", n = 50)
# by index
pal(1, n = 10)
# with transparency
pal("helsana", n = 5, opacity = 0.5)
# show all names
palNames()
List Available Palette Names
Description
Returns the names of all palettes available in pal(),
optionally filtered by type.
Usage
palNames(type = c("all", "continuous", "discrete"))
Arguments
type |
character, one of |
Value
a character vector of palette names.
See Also
Other color.palettes:
hcol(),
pal()
Examples
palNames()
palNames("continuous")
palNames("discrete")
Bland-Altman Plot
Description
Plots a Bland-Altman agreement analysis.
Usage
## S3 method for class 'BlandAltman'
plot(
x,
main = "",
xlab = "Mean",
ylab = "Difference",
xlim = NULL,
ylim = NULL,
pch = 16,
col = NULL,
grid = TRUE,
meanLine = TRUE,
limits = TRUE,
cband = FALSE,
trend = FALSE,
showText = TRUE,
stamp = NULL,
...
)
Arguments
x |
an object of class |
main |
plot title. |
xlab |
X-axis label. |
ylab |
Y-axis label. |
xlim |
X-axis limits. |
ylim |
Y-axis limits. |
pch |
plotting symbol. |
col |
point colour. |
grid |
logical; draw a background grid. |
meanLine |
logical; draw the bias line. |
limits |
logical; draw the limits of agreement. |
cband |
logical; draw confidence bands. |
trend |
logical; draw a regression line of differences versus means. |
showText |
logical; annotate bias and limits. |
stamp |
optional plot stamp. |
... |
further arguments passed to |
Details
Objects of class "BlandAltman" are typically created with
DescToolsX::blandAltmanData(). The method uses the elements mean
and diff (one value per pair), bias, loaLower and loaUpper, and
for the confidence bands biasCI, loaLowerCI and loaUpperCI (each
a vector of length 2).
Value
Invisibly returns x.
See Also
Other plot.s3:
plot.Desc.qn(),
plot.Desc.table(),
plot.Lc()
Examples
# two measurement methods applied to the same 40 subjects; the object is
# built by hand here, normally DescToolsX::blandAltmanData() returns it
set.seed(1)
a <- rnorm(40, mean = 100, sd = 15)
b <- a + rnorm(40, mean = 2, sd = 5)
d <- a - b
n <- length(d)
s <- sd(d)
tq <- qt(0.975, df = n - 1)
loa <- mean(d) + c(-1, 1) * 1.96 * s
seLoa <- sqrt(3 * s^2 / n)
ba <- structure(list(
mean = (a + b) / 2,
diff = d,
bias = mean(d),
biasCI = mean(d) + c(-1, 1) * tq * s / sqrt(n),
loaLower = loa[1],
loaUpper = loa[2],
loaLowerCI = loa[1] + c(-1, 1) * tq * seLoa,
loaUpperCI = loa[2] + c(-1, 1) * tq * seLoa
), class = "BlandAltman")
plot(ba, main = "Method A vs. method B")
plot(ba, cband = TRUE, trend = TRUE)
Plot Method for Numeric-Categorical Desc Objects
Description
Visualises the relationship between a numeric variable and a categorical
variable, as computed by DescToolsX::desc(y ~ x) (or x ~ y) for
a numeric/categorical pair. Five panel types are available, selectable
(and combinable) via which.
Usage
## S3 method for class 'Desc.qn'
plot(
x,
main = NULL,
xlab = NULL,
ylab = NULL,
which = 2,
verbose = NULL,
col = .useTheme,
box = .useTheme,
legend = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
an object of class |
main |
main title. |
xlab |
x-axis label. |
ylab |
y-axis label. |
which |
integer vector selecting one or more panels to draw, in the given order. One or more of:
Selecting multiple panels does not change the plotting layout (no
implicit |
verbose |
integer; currently computed from
|
col |
color specification.
Supplying |
box |
controls the plot frame for panels 4 and 5.
|
legend |
controls the legend for panel 3 (grouped density curves).
|
stamp |
controls the corner stamp. |
... |
further graphical parameters, passed to |
Details
The left margin is sized automatically from the longest of: the
(possibly panel-specific) y-axis labels, and - for panels 1/2 - the
categorical level names drawn as axis tick labels, so neither is ever
clipped regardless of which.
Value
Invisibly returns x.
See Also
DescToolsX::desc, plotDens(), plotBox(),
graphics::cdplot(), graphics::spineplot()
Other plot.s3:
plot.BlandAltman(),
plot.Desc.table(),
plot.Lc()
Examples
# the object is built by hand here; normally DescToolsX::desc(y ~ x)
# returns it for a numeric-categorical pair
d <- structure(list(
res = list(xOk = ToothGrowth$len,
yOk = ToothGrowth$supp,
lvls = levels(ToothGrowth$supp),
k = nlevels(ToothGrowth$supp)),
meta = list(xname = "len", yname = "supp")
), class = "Desc.qn")
plot(d) # spineplot
plot(d, which = 3) # density by group
plot(d, which = 4) # boxplot by group
Plot Method for Categorical-Categorical Desc Objects
Description
Visualises a (two-dimensional) cross-tabulation, as computed by
DescToolsX::desc() for a categorical/categorical pair.
Four panel types are available, selectable (and combinable) via
which. Higher-dimensional tables (more than two margins) are not
supported; a message is issued and the call returns invisibly.
Usage
## S3 method for class 'Desc.table'
plot(
x,
main = NULL,
xlab = NULL,
ylab = NULL,
which = 1,
verbose = NULL,
col = .useTheme,
box = .useTheme,
stamp = .useTheme,
...
)
Arguments
x |
an object of class |
main |
main title. |
xlab |
x-axis label. |
ylab |
y-axis label. |
which |
integer vector selecting one or more panels to draw, in the given order. One or more of:
Selecting multiple panels does not change the plotting layout (no
implicit |
verbose |
integer; currently computed from
|
col |
color specification.
Supplying |
box |
controls the plot frame.
|
stamp |
controls the corner stamp. |
... |
further graphical parameters, passed to |
Details
The left margin is sized automatically from the longest of: the y-axis
label, and - for panels 1/2 - the row names of tab drawn as
axis tick labels, so neither is ever clipped regardless of which.
Only two-dimensional tables are supported. If x carries a table
with more than two margins, a message is issued and the function returns
invisibly without drawing anything.
Value
Invisibly returns x.
See Also
DescToolsX::desc, plotAssoc(),
plotHeatmap(), plotMosaic(),
graphics::spineplot()
Other plot.s3:
plot.BlandAltman(),
plot.Desc.qn(),
plot.Lc()
Examples
# the object is built by hand here; normally DescToolsX::desc()
# returns it for a pair of categorical variables
d <- structure(list(
tab = margin.table(HairEyeColor, c(1, 2)),
meta = list(xname = "Hair ~ Eye")
), class = "Desc.table")
plot(d) # spineplot
plot(d, which = 2) # mosaic plot
Plot Methods for Lorenz Curve Objects
Description
Visualize objects of class "Lc" and "LcList" returned by
DescToolsX::lc(). The plot() method draws a new
Lorenz curve plot including the line of perfect equality; lines()
and points() add to an existing plot.
Usage
## S3 method for class 'Lc'
plot(
x,
main = NULL,
xlab = NULL,
ylab = NULL,
xlim = NULL,
ylim = NULL,
general = FALSE,
col = NULL,
line = TRUE,
points = NULL,
eqline = TRUE,
grid = .useTheme,
box = .useTheme,
cband = NA,
stamp = .useTheme,
...
)
## S3 method for class 'Lc'
lines(x, general = FALSE, col = NULL, lwd = 2, lty = 1, cband = NA, ...)
## S3 method for class 'Lc'
points(x, general = FALSE, pch = 16, col = NULL, ...)
## S3 method for class 'LcList'
lines(x, col = NULL, ...)
## S3 method for class 'LcList'
points(x, col = NULL, ...)
## S3 method for class 'LcList'
plot(x, col = NULL, general = FALSE, ylim = NULL, ...)
Arguments
x |
object of class |
main, xlab, ylab |
main title and axis labels, used by
|
xlim, ylim |
numeric vectors of length 2 giving axis limits, used by
|
general |
logical. If |
col |
color of curve and symbols. For |
line |
logical or list, used by |
points |
|
eqline |
logical or list, used by |
grid, box |
callIf-style specs for the grid and the box around the
plot region, used by |
cband |
used by |
stamp |
controls the corner stamp. |
... |
further arguments. For |
lwd |
line width, used by |
lty |
line type, used by |
pch |
plotting symbol, used by |
Details
For "LcList" objects (grouped Lorenz curves), plot() draws
the first group and overlays the remaining groups with lines().
Colors cycle automatically when col is not supplied and are
recycled to the number of groups otherwise.
The curve of plot.Lc() is drawn by lines.Lc() and the
symbols by points.Lc(), so all three methods share one code path
and one set of semantics - including the confidence band, which is
controlled by cband in plot.Lc() exactly as it is in
lines.Lc(). Pass a list of arguments to
DescToolsX::predict.Lc() to control the bootstrap (e.g.
cband = list(conf.level = 0.90, n = 500)). Set
cband = NA (default) to suppress the band. Note that
line = FALSE suppresses the band along with the curve.
With general = TRUE the generalized Lorenz curve is displayed.
It ends at the mean rather than at 1, so the default ylim and the
slope of the equality line follow the data; for "LcList" objects
the panel is sized to accommodate all groups, not just the first.
Value
All methods return NULL invisibly.
See Also
DescToolsX::lc() for computing the Lorenz curve,
DescToolsX::predict.Lc() for bootstrap confidence
intervals, DescToolsX::gini() for the Gini coefficient.
Other plot.s3:
plot.BlandAltman(),
plot.Desc.qn(),
plot.Desc.table()
Examples
# Lorenz curve objects are built by hand here; normally
# DescToolsX::lc() returns them
lorenz <- function(v) {
v <- sort(v)
L <- c(0, cumsum(v)) / sum(v)
structure(list(p = c(0, seq_along(v)) / length(v),
L = L, L.general = L * mean(v)),
class = "Lc")
}
set.seed(4)
even <- lorenz(rgamma(50, shape = 8))
skewed <- lorenz(rlnorm(50, sdlog = 1.2))
plot(skewed, main = "Lorenz curves")
lines(even, col = "steelblue")
# several groups at once, generalized curves
grp <- structure(list(even = even, skewed = skewed), class = "LcList")
plot(grp, general = TRUE, col = c("steelblue", "darkred"))
Stacked Area Plot
Description
Draws one or several stacked area series using cumulative polygons.
The function accepts either a matrix of values or separate x and
y coordinates. Multiple series are displayed as stacked areas.
Usage
plotArea(
x,
y,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
prop = FALSE,
col = NULL,
grid = .useTheme,
legend = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector, matrix or data frame. If |
y |
optional numeric vector or matrix giving the y-values. If supplied,
|
main |
main title of the plot. |
xlab |
label for the x-axis. |
ylab |
label for the y-axis. |
xlim |
limits for the x-axis. |
ylim |
limits for the y-axis. |
prop |
logical indicating whether rows should be converted to proportions so that stacked areas sum to one. |
col |
fill colours used for the areas. |
grid |
controls the background grid. |
legend |
logical or list controlling the legend. If |
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to |
Details
If y is missing, x is interpreted as a matrix and each column
is drawn as a separate stacked area.
The cumulative sums are calculated row-wise and displayed as polygons stacked on top of each other.
If prop = TRUE, each row is converted to proportions before plotting,
so the stacked areas sum to one.
Row names are used as x-axis labels when available and y is omitted.
Value
Invisibly returns a list containing:
-
xthe x-values used for plotting, -
ythe original y-values, -
cumulativethe cumulative values used to construct the areas, -
legendthe legend specification if drawn.
See Also
Other plot.univariate:
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
plotArea(VADeaths)
plotArea(
WorldPhones,
col = pal("helsana")
)
plotArea(
WorldPhones,
prop = TRUE,
col = rainbow(ncol(WorldPhones))
)
x <- 1:20
y <- cbind(
A = runif(20, 1, 5),
B = runif(20, 1, 3),
C = runif(20, 1, 4)
)
plotArea(x, y)
Association Plot for Contingency Tables
Description
Plots an association plot (Cohen-Friendly plot) for a two-dimensional contingency table. Cells are drawn with widths proportional to the square root of expected frequencies and heights proportional to Pearson residuals. Color encodes both the direction and strength of the association using a diverging palette.
Usage
plotAssoc(
x,
main = NULL,
xlab = TRUE,
ylab = TRUE,
space = 0.3,
reorder = TRUE,
col = pal("red-white-blue-3", n = 100L),
border = NA,
labels = FALSE,
stamp = .useTheme,
...
)
Arguments
x |
a two-dimensional contingency table ( |
main |
main title. |
xlab |
character, x-axis label. Defaults to the first dimension name. |
ylab |
character, y-axis label. Defaults to the second dimension name. |
space |
numeric, fraction of average cell width/height used as gap
between cells. Default |
reorder |
logical. If |
col |
character vector of colors for the diverging palette. Default
uses |
border |
the color of the border |
labels |
logical or character. If |
stamp |
controls the corner stamp. |
... |
further arguments passed to |
Details
The plot is based on the association plot described in Cohen (1980) and
Friendly (1992). Each cell (i,j) is represented by a rectangle:
-
width proportional to
\sqrt{e_{ij}}(square root of expected frequency) -
height proportional to the Pearson residual
d_{ij} = (f_{ij} - e_{ij}) / \sqrt{e_{ij}}
A horizontal baseline at zero represents independence. Cells above the baseline indicate positive association, cells below negative association.
Color encodes both direction and magnitude: the diverging palette runs from the negative color (strong negative residual) through white (no association) to the positive color (strong positive residual).
Value
A list with the components x and y, returned invisibly: the
horizontal centres of the bars, one per column of the table, and the
baselines of the residuals, one per row. Both are named by the levels and
given in the order in which they are drawn.
References
Cohen, A. (1980). On the graphical display of the significant components of a two-way contingency table. Communications in Statistics — Theory and Methods, 9, 1025–1041.
Friendly, M. (1992). Graphical methods for categorical data. SAS User Group International Conference Proceedings, 17, 190–200.
See Also
graphics::mosaicplot, DescToolsX::confusion
Other plot.bivariate:
plotBag(),
plotBubble(),
plotCor(),
plotDens2D(),
plotHeatmap(),
plotHexbin(),
plotMosaic(),
plotXY()
Examples
tab <- table(bedrock::Pizza$driver, bedrock::Pizza$area)
# default
plotAssoc(tab)
# custom palette
plotAssoc(tab, col = pal("red-white-green", n = 100))
# with residual labels
plotAssoc(tab, labels = TRUE)
# no reordering
plotAssoc(tab, reorder = FALSE)
plotAssoc(tab,
main = "Association Driver ~ Area",
cutoff = 1,
xlab="Driver", ylab="Area")
cols <- pal()[c(12, 8)]
plotAssoc(tab,
main = "Association Driver ~ Area",
cutoff = 1,
col = fade(cols, 0.7), border = cols,
reorder = TRUE, cex.axis = 0.9,
xlab = list(labels = "Driver ",
col = "#5B2A45", cex = 1.1),
ylab = NA, labels = TRUE)
Create a Bagplot (Bivariate Boxplot)
Description
Draws a bagplot (bivariate boxplot) based on halfspace (Tukey) depth.
The bag contains the innermost 50\
hull of all non-outlying points, and points outside the fence (the bag
inflated by factor, not drawn) are flagged as outliers.
Usage
plotBag(x, ...)
## S3 method for class 'formula'
plotBag(
formula,
data,
subset,
na.action = na.omit,
main = NULL,
xlab = NULL,
ylab = NULL,
...
)
## Default S3 method:
plotBag(
x,
main = NULL,
xlab = NULL,
ylab = NULL,
xlim = NULL,
ylim = NULL,
factor = 3,
eps = 1e-08,
dither = FALSE,
points = TRUE,
bag = TRUE,
loop = TRUE,
fence = FALSE,
out = TRUE,
median = TRUE,
grid = FALSE,
box = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
a numeric matrix or data frame with exactly two columns, or a
formula of the form |
... |
additional graphical parameters passed to |
formula |
a formula of the form |
data |
an optional data frame containing the variables in
|
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled.
Defaults to |
main |
main title. |
xlab, ylab |
axis labels. |
xlim, ylim |
numeric vectors of length 2 specifying axis limits.
|
factor |
inflation factor for the fence (default: 3). |
eps |
numeric tolerance used in depth computation and geometry, relative to the standardized coordinates. |
dither |
logical, whether to add small noise (order |
points, bag, loop, fence, out, median, grid, box |
object-oriented control of plot elements (see Details). |
stamp |
controls the corner stamp. |
Details
All graphical elements are controlled via an object-oriented interface:
each element can be specified as TRUE, FALSE, or a
list(...) of graphical parameters. Internally, this is handled
via bedrock::callIf().
The construction follows Rousseeuw, Ruts and Tukey (1999):
The halfspace (Tukey) depth of every observation is computed using a direct port of the original Fortran routine
TUKDEPTH(Rousseeuw & Ruts, 1996).The Tukey median is approximated by the mean of all observations with maximal depth.
The bag is obtained by radial interpolation between the convex hulls of two adjacent depth regions, calibrated such that it contains
\lfloor n/2 \rfloorobservations (up to ties on the polygon boundary).The fence is the bag inflated by
factorrelative to the Tukey median. Following the original proposal it is used for classification only and not drawn by default.Observations outside the fence are flagged as outliers.
The loop is the convex hull of all non-outlying observations, so it always lies within the data range.
Two approximations remain relative to the strict theory: the Tukey
median is not computed via HALFMED, and the bag interpolates
hulls of sample depth regions rather than exact isodepth contours.
Borderline outlier classifications may therefore differ slightly from
other implementations (e.g. aplpack).
The depth computation handles exact ties and collinear configurations (e.g. discrete data) exactly; no dithering is needed. All computations run on standardized coordinates, so the result does not depend on the units of measurement.
Value
Invisibly returns a list of class "bagplot" with
components:
-
center- Tukey median. -
depth- depth of the innermost region bounding the bag. -
bag- bag polygon (matrix). -
fence- fence polygon (matrix, not drawn by default). -
loop- loop polygon (matrix). -
outliers- outlier points (matrix). -
depths- halfspace depth of all observations.
Element Control
Each of the following arguments accepts:
-
TRUE- draw element with defaults -
FALSE- suppress element -
list(...)- customize graphical parameters
Supported elements (in drawing order):
-
grid- background grid -
fence- classification boundary (defaultFALSE) -
loop- convex hull of the non-outlying points -
bag- central 50\ -
points- raw data points -
out- outliers -
median- Tukey median -
box- plot frame
Note
The halfspace depth is computed by a C++ port of the Fortran routine
TUKDEPTH (Algorithm AS 307, Rousseeuw & Ruts 1996), taken from
src/depth.f of the archived package 'depth' by M. Genest,
J.-C. Massé and J.-F. Plante.
References
Rousseeuw, P. J., Ruts, I., & Tukey, J. W. (1999). The bagplot: A bivariate boxplot. The American Statistician, 53(4), 382–387. doi:10.1080/00031305.1999.10474494
Rousseeuw, P. J., & Ruts, I. (1996). Algorithm AS 307: Bivariate location depth. Journal of the Royal Statistical Society, Series C (Applied Statistics), 45(4), 516–526. doi:10.2307/2986073
See Also
Other plot.bivariate:
plotAssoc(),
plotBubble(),
plotCor(),
plotDens2D(),
plotHeatmap(),
plotHexbin(),
plotMosaic(),
plotXY()
Examples
set.seed(1)
x <- cbind(rnorm(200), rnorm(200))
# data of Rousseeuw et al. (1999): car weight vs engine displacement
cardata <- data.frame(
Weight = c(2560, 2345, 1845, 2260, 2440,
2285, 2275, 2350, 2295, 1900, 2390, 2075, 2330, 3320, 2885,
3310, 2695, 2170, 2710, 2775, 2840, 2485, 2670, 2640, 2655,
3065, 2750, 2920, 2780, 2745, 3110, 2920, 2645, 2575, 2935,
2920, 2985, 3265, 2880, 2975, 3450, 3145, 3190, 3610, 2885,
3480, 3200, 2765, 3220, 3480, 3325, 3855, 3850, 3195, 3735,
3665, 3735, 3415, 3185, 3690),
Disp = c(97, 114, 81, 91, 113, 97, 97,
98, 109, 73, 97, 89, 109, 305, 153, 302, 133, 97, 125, 146,
107, 109, 121, 151, 133, 181, 141, 132, 133, 122, 181, 146,
151, 116, 135, 122, 141, 163, 151, 153, 202, 180, 182, 232,
143, 180, 180, 151, 189, 180, 231, 305, 302, 151, 202, 182,
181, 143, 146, 146)
)
plotBag(x)
# Custom styling
plotBag(x,
bag = list(col = adjustcolor("green", 0.3), border = "darkgreen"),
loop = list(border = "black", lty = 3),
out = list(col = "red", pch = 17),
grid = TRUE
)
# Minimal plot
plotBag(x, points = FALSE, median = FALSE)
# formula interface
plotBag(Disp ~ Weight, data = cardata)
# subset, evaluated in data
plotBag(Disp ~ Weight, data = cardata, subset = Weight > 2500)
# example of Rousseeuw et al. (1999): car weight vs engine displacement;
# the axis labels default to the column names
plotBag(cardata)
Themed Barplot with Grid, Labels and Optional Connecting Lines
Description
Creates a themed wrapper around graphics::barplot() with
support for consistent styling, optional grid lines, value labels,
and connecting lines for stacked barplots.
Usage
plotBar(
height,
main = NULL,
xlab = NULL,
ylab = NULL,
yax = NULL,
beside = FALSE,
horiz = FALSE,
col = .useTheme,
border = .useTheme,
grid = .useTheme,
box = FALSE,
text = NULL,
legend = TRUE,
connLines = NULL,
stamp = .useTheme,
...
)
Arguments
height |
A vector or matrix of bar heights passed directly to
|
main |
main title. |
xlab, ylab |
optional axis labels. Defaults follow base graphics behaviour. |
yax |
controls drawing of the numeric axis. Supported values are
|
beside |
logical. If |
horiz |
logical. If |
col |
bar fill colours. |
border |
bar border colour. |
grid |
controls drawing of grid lines. Can be:
|
box |
controls drawing of the plot box. |
text |
optional list of arguments passed to |
legend |
controls the legend explaining the rows of a matrix.
|
connLines |
optional list of arguments controlling connecting
lines between stacked bars. Only supported when
|
stamp |
controls the corner stamp. |
... |
additional arguments passed to |
Details
The function first initializes the plotting region invisibly using
graphics::barplot(), optionally adds grid lines, and then
draws the actual bars and additional layers (axis, connecting lines,
text labels).
The function internally performs the following steps:
Draws an invisible
barplotto establish the coordinate system.Optionally adds grid lines.
Draws the bars.
Draws the numeric axis if enabled.
Optionally adds connecting lines for stacked bars.
Optionally adds value labels via
barText().Optionally draws a box around the plot region.
Graphical parameters such as bg, cex, las,
mar, etc. can be supplied via ....
The precedence of theme-aware settings (col, border,
grid, box, stamp) is
explicit argument > function-specific default > active theme (getTheme())
Value
Invisibly returns the midpoints of the bars as returned by
graphics::barplot().
See Also
graphics::barplot, barText, theme
Other plot.univariate:
plotArea(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
# Simple barplot
plotBar(1:5)
# With grid lines
plotBar(1:5, grid = TRUE)
# Stacked bars with labels and connecting lines
m <- matrix(c(3,2,4,1,5,2), nrow = 2)
plotBar(m,
text = list(pos = "mid"),
connLines = list(col = "black"))
# a matrix: one shade per row, with a legend
plotBar(VADeaths)
# Grouped bars
plotBar(VADeaths,
beside = TRUE,
col = gray.colors(nrow(VADeaths)))
# Horizontal bars
plotBar(VADeaths,
horiz = TRUE,
las = 1)
plotBar(VADeaths, ylim=c(0,250),
grid=list(col = "grey", lty="dotted"),
las=1, main="MyTitle",
text = list(labels=VADeaths,
border = NA, srt=45, bg="navajowhite"))
plotBar(VADeaths, ylim=c(0,80),
las=1, main="MyTitle",
box=FALSE,
col=gray.colors(nrow(VADeaths)),
beside=TRUE,
text = list(col="red", bg=addOpacity("white", 0.7), border=NA))
plotBar(VADeaths, connLines = list(lwd=1, col="blue"),
box=FALSE, las=1, main="Connecting Lines")
ptab <- proportions(VADeaths, margin=2)
plotBar(ptab,
las=1, main="VADeaths in %",
box=FALSE, horiz=TRUE,
col=(cols <- gray.colors(nrow(VADeaths))),
beside=FALSE,
text = list(labels=fm(ptab, fmt="%"), border=NA,
col=contrastCol(cols)))
plotBar(VADeaths/1e3, box=FALSE, bg="lightyellow", main="VADeaths",
horiz=TRUE,
text=list(border=FALSE, cex=0.8, col=c("blue", "green","orange")),
mar=c(right=5),
yax = list(fmt="%", d=0, big=",",
col="red", col.axis="blue", lwd=2))
Binary Tree
Description
Create a binary tree of a given number of nodes n. Can be used to
organize a sorted numeric vector as a binary tree.
Usage
plotBinaryTree(
x,
main = "Binary tree",
horiz = FALSE,
text = TRUE,
line = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector to be organized as binary tree. |
main |
main title of the plot. |
horiz |
logical, should the plot be oriented horizontally or vertically (default). |
text |
properties of the text, can be any of the arguments
of |
line |
properties of the line segments ( |
stamp |
controls the corner stamp. |
... |
the dots are sent to |
Details
If we index the nodes of the tree as 1 for the top, 2–3 for the next horizontal row, 4–7 for the next, ... then the parent-child traversal becomes particularly easy. The basic idea is that the rows of the tree start at indices 1, 2, 4, ....
binaryTree(13) yields the vector c(8, 4, 9, 2, 10, 5, 11, 1, 12, 6, 13, 3, 7) meaning that the smallest element will be in position 8 of the tree,
the next smallest in position 4, etc.
Value
an integer vector of length n
Note
Substantially based on code by Terry Therneau, with major extensions and improvements by the package author.
See Also
Other plot.special:
plotCirc(),
plotLift(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
bedrock::binaryTree(12)
x <- sort(sample(100, 24))
z <- plotBinaryTree(x, cex=0.8)
plotBinaryTree(LETTERS[1:15],
text=list(col="deeppink4", cex=2),
line=list(col="navajowhite3", lwd=2))
# Plot example - Titanic data, for once from a somwhat different perspective
tab <- apply(Titanic, c(2,3,4), sum)
cprob <- c(1, prop.table(apply(tab, 1, sum))
, as.vector(aperm(prop.table(apply(tab, c(1,2), sum), 1), c(2, 1)))
, as.vector(aperm(prop.table(tab, c(1,2)), c(3,2,1)))
)
plotBinaryTree(round(cprob[bedrock::binaryTree(length(cprob))],2), horiz=TRUE, cex=0.8,
main="Titanic")
text(c("sex","age","survived"), y=0, x=c(1,2,3)+1)
Grouped Boxplot
Description
Draws boxplots for a numeric variable, optionally grouped by a categorical variable. Group means and a reference line for the overall mean can optionally be overlaid.
Usage
plotBox(x, ...)
## Default S3 method:
plotBox(
x,
groups = NULL,
order = NULL,
horiz = FALSE,
main = NULL,
xlab = "",
ylab = "",
ylim = NULL,
col = NULL,
grid = TRUE,
means = TRUE,
stamp = .useTheme,
...
)
## S3 method for class 'formula'
plotBox(
formula,
data,
subset,
na.action = na.omit,
horiz = FALSE,
main = NULL,
xlab = "",
ylab = "",
...
)
Arguments
x |
numeric vector, or a formula of the form |
... |
graphical parameters. Parameters recognized by the
internal graphics framework are applied via |
groups |
optional grouping variable (ignored if a formula is used). |
order |
optional order of the groups along the group axis: a
character vector of group levels, e.g.
|
horiz |
logical. If |
main |
main title. |
xlab |
label for the x-axis, i.e. the horizontal axis as drawn
(the value axis if |
ylab |
label for the y-axis, i.e. the vertical axis as drawn
(the group axis if |
ylim |
numeric vector of length 2 specifying the limits of the value
axis (the x-axis if |
col |
vector of fill colors, recycled over the groups. |
grid |
controls drawing of the background grid. Can be:
|
means |
controls drawing of group means and an overall mean reference line. The reference line is drawn only for more than one group; with a single box it would merely repeat its mean. Can be:
|
stamp |
controls the corner stamp. |
formula |
a formula of the form |
data |
an optional data frame containing the variables in the formula. |
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled,
defaults to |
Details
Optional plot components are controlled using
bedrock::callIf() semantics:
-
TRUE: draw with defaults -
FALSE,NULL, orNA: suppress component named list: customize component arguments
Value
Invisibly returns NULL.
See Also
graphics::boxplot(),
bedrock::callIf()
Other plot.univariate:
plotArea(),
plotBar(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
set.seed(1)
x <- rnorm(100)
g <- sample(c("A", "B"), 100, TRUE)
plotBox(x)
plotBox(x, g)
plotBox(x ~ g)
# data, subset and the cells of two grouping variables
plotBox(len ~ supp, ToothGrowth, subset = dose > 0.5)
plotBox(len ~ supp:dose, ToothGrowth)
# horizontal boxes
plotBox(len ~ supp:dose, ToothGrowth, horiz = TRUE)
# groups in a chosen order, e.g. by median
plotBox(Sepal.Length ~ Species, data = iris,
order = c("versicolor", "virginica", "setosa"))
med <- tapply(iris$Sepal.Length, iris$Species, median)
plotBox(Sepal.Length ~ Species, data = iris, order = order(med))
Bubble Plot
Description
Draws a bubble plot where the position is given by x and y,
and the size of each bubble increases with area.
Usage
plotBubble(x, ...)
## Default S3 method:
plotBubble(
x,
y,
area,
main = "",
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
add = FALSE,
col = NA,
border = NULL,
cex = 1,
grid = NA,
na.rm = FALSE,
stamp = .useTheme,
...
)
## S3 method for class 'formula'
plotBubble(
formula,
data = NULL,
subset,
na.action = na.omit,
main = "",
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
add = FALSE,
col = NA,
border = NULL,
cex = 1,
grid = NA,
...
)
Arguments
x |
numeric vector of x positions. |
... |
additional graphical parameters passed to |
y |
numeric vector of y positions. |
area |
non-negative numeric vector controlling the bubble sizes. |
main, xlab, ylab |
plot labels. |
xlim, ylim |
axis limits. |
add |
logical; if |
col |
fill color(s) of the bubbles. |
border |
border color(s) of the bubbles. |
cex |
scaling factor applied to the bubble radii. |
grid |
logical, |
na.rm |
logical. Observations with a missing |
stamp |
controls the corner stamp. |
formula |
A formula of the form |
data |
optional data frame. |
subset |
optional subset expression, evaluated in |
na.action |
function to handle missing values, defaults to
|
Details
The function supports both a default interface and a formula interface
of the form y ~ x | area.
The bubble radii are scaled relative to the largest area: the largest
bubble gets a radius of 0.35 * cex inches, the others
r = 0.35 \cdot cex \cdot (area / \max(area))^{0.4}. The exponent
0.4 (instead of 0.5 for strictly area-proportional circles) dampens the
size differences, so that small bubbles remain visible. Radii are
converted to user coordinates separately for both axes, so the bubbles
are drawn as circles regardless of the aspect ratio.
Bubbles are drawn in order of decreasing area, so small bubbles are not hidden behind large ones.
Graphical elements such as grids are controlled via the unified plot
design system using bedrock::callIf() and .theme().
Value
Invisibly, a data frame with one row per drawn bubble and the
columns x, y, area, col, border, and the radii rx, ry in
user coordinates, sorted by decreasing area.
See Also
Other plot.bivariate:
plotAssoc(),
plotBag(),
plotCor(),
plotDens2D(),
plotHeatmap(),
plotHexbin(),
plotMosaic(),
plotXY()
Examples
set.seed(1)
x <- rnorm(100)
y <- rnorm(100)
a <- runif(100, 1, 10)
plotBubble(x, y, a)
df <- data.frame(x = x, y = y, a = a)
plotBubble(y ~ x | a, data = df)
US <- data.frame(state.x77, State=state.name,
Region=state.region, Abb=state.abb)
plotBubble(Income ~ Population | Area ,
data=US,
grid=TRUE, col=addOpacity(pal("helsana")[US$Region]), cex=1.2 )
text(Income ~ Population, US, labels=US$Abb, cex=0.8)
Categorical Distribution Plot
Description
Visualizes the distribution of a categorical variable using horizontal bar plots of absolute and relative frequencies. Optionally, cumulative proportions (ECDF-style) can be displayed.
Usage
plotCatDist(
x,
main = NULL,
type = c("both", "freq", "perc"),
ecdf = FALSE,
maxCats = NULL,
maxLabLen = 25,
col = "grey80",
border = FALSE,
stamp = .useTheme,
...
)
Arguments
x |
a factor or character vector, a one-dimensional table of counts, or a numeric vector of precomputed frequencies. Unnamed numeric frequency vectors are labelled by their positions. |
main |
plot title. |
type |
character; one of |
ecdf |
logical; if |
maxCats |
optional maximum number of categories to display (truncates if exceeded). |
maxLabLen |
integer; maximum length of category labels before truncation. |
col |
fill color for bars. |
border |
logical; draw borders around bars. |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to |
Details
The function produces horizontal bar plots:
Absolute frequencies (counts)
Relative frequencies (percentages) or cumulative proportions
If type = "both", both views are shown side by side.
Long labels are truncated, and large category sets can be limited via
maxCats.
Raw categorical data and their pre-tabulated form are treated identically.
When categories are truncated via maxCats, proportions remain based
on the total frequency before truncation.
Value
Invisibly returns a list with frequencies and proportions.
See Also
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
# Basic usage
x <- factor(sample(letters[1:5], 100, TRUE))
plotCatDist(x)
plotCatDist(table(x))
# Only proportions
plotCatDist(x, type = "perc")
# With cumulative distribution
plotCatDist(x, ecdf = TRUE)
# Many categories (truncation)
x2 <- factor(sample(letters, 200, TRUE))
plotCatDist(x2, maxCats = 10)
Circular Chord Diagram
Description
Draws a chord diagram of a two-way table: the categories of the rows lie as sectors on the right half of a circle, those of the columns on the left half, and every cell of the table is a ribbon between its row and its column sector whose width is proportional to its value.
Usage
plotCirc(
x,
main = NULL,
gap = 3,
opacity = 0.5,
sector = TRUE,
ribbon = TRUE,
labels = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
a numeric matrix or two-way table with non-negative entries. Rows and columns are the two sets of categories; the dimnames give the labels. |
main |
main title. |
gap |
gap between two sectors, in degrees. |
opacity |
opacity of the default ribbon colors, between 0 and 1. |
sector |
sector styling. Can be:
Colors are given for the rows followed by the columns of |
ribbon |
ribbon styling. Can be:
|
labels |
label styling. Can be:
|
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to |
Details
The size of a sector is the margin total of its category. Within a row sector the ribbons are ordered like the column sectors they lead to, within a column sector like the row sectors, both from top to bottom; this keeps crossings few. Empty cells draw no ribbon.
The plot region is enlarged as far as needed for the labels, so that long category names are not cut off.
Value
Invisibly, a list with the data frame sectors (category,
margin ("row" or "col"), total, start and end angle in radians,
color) and the label positions x and y.
See Also
Other plot.special:
plotBinaryTree(),
plotLift(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
set.seed(1)
x <- matrix(sample(1:10, 36, replace = TRUE), nrow = 6,
dimnames = list(LETTERS[1:6], letters[1:6]))
plotCirc(x)
# a contingency table, radial labels
plotCirc(HairEyeColor[, , "Female"], labels = list(las = 2))
# own colors and white borders
plotCirc(x,
sector = list(col = hcol(), border = "white"),
ribbon = list(border = "white"))
Correlation Matrix Plot with Theming and Optional Labels
Description
Draws a correlation matrix using graphics::image() with
optional clustering, triangular display, grid lines, color legend,
and numeric labels inside the cells.
Usage
plotCor(
x,
main = NULL,
xlab = NULL,
ylab = NULL,
xax = TRUE,
yax = TRUE,
minCor = 0,
cluster = FALSE,
triangle = c("full", "upper", "lower"),
diag = TRUE,
col = .useTheme,
grid = .useTheme,
box = .useTheme,
legend = TRUE,
text = FALSE,
stamp = .useTheme,
...
)
Arguments
x |
A numeric correlation matrix. |
main, xlab, ylab |
optional plot labels. |
xax, yax |
controls drawing of the axes. Supported values are
|
minCor |
numeric threshold; correlations with absolute value
smaller than this are suppressed (set to |
cluster |
logical; if |
triangle |
which part of the matrix to display.
One of
|
diag |
logical; should the diagonal be displayed. |
col |
color palette used for the correlation values. |
grid |
controls drawing of cell-separator grid lines at the half-integer matrix boundaries (clipped to the matrix extent, so they never bleed into the margins). Can be:
|
box |
controls drawing of the plot box. |
legend |
logical; draw a color legend for the correlation scale. |
text |
controls numeric labels drawn inside the matrix cells. Supported values are
|
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to
|
Details
The function follows the DescToolsX plotting conventions:
User arguments override theme settings.
Theme settings override base graphics defaults.
Graphical parameters (e.g.
cex,las,mar) can be supplied via....
The function internally:
Optionally reorders the matrix using hierarchical clustering.
Masks parts of the matrix according to
triangleanddiag.Adjusts plot margins based on label sizes.
Draws the matrix using
graphics::image().Optionally adds grid lines, numeric labels, axes, and a color legend.
Grid lines are drawn via clipped graphics::abline() calls
at the matrix's half-integer cell boundaries rather than via
graphics::grid(): grid()'s nx/ny
divide the full plot region (par("usr")), which may carry axis
padding unrelated to image()'s integer cell geometry, whereas the
clipped approach stays exact regardless of that padding.
Value
Invisibly returns the (possibly reordered) matrix used for plotting.
See Also
graphics::image(), stats::cor(),
theme
Other plot.bivariate:
plotAssoc(),
plotBag(),
plotBubble(),
plotDens2D(),
plotHeatmap(),
plotHexbin(),
plotMosaic(),
plotXY()
Examples
m <- cor(swiss)
# full correlation matrix
plotCor(m, legend=FALSE)
# upper triangle only
plotCor(m, triangle = "upper")
# clustered variables
plotCor(m, cluster = TRUE)
# with correlation values
plotCor(m, text = TRUE)
# customized labels
plotCor(m,
text = list(col = "black", cex = 0.9))
# hide grid
plotCor(m, grid = FALSE)
plotCor(m, col=colorRampPalette(c("red", "black", "green"), space = "rgb")(20))
plotCor(m, col=colorRampPalette(c("red", "black", "green"), space = "rgb")(20),
legend=FALSE)
m <- cor(mtcars)
plotCor(m, col=pal("red-white-blue-1", 100), border="grey",
legend=list(labels=format(seq(-1,1,.25), digits=2), box=list(border="grey")))
# display only correlation with a value > 0.7
plotCor(m, minCor = 0.7)
x <- matrix(rep(1:ncol(m),each=ncol(m)), ncol=ncol(m))
y <- matrix(rep(ncol(m):1,ncol(m)), ncol=ncol(m))
txt <- format(m, digits=3)
idx <- upper.tri(matrix(x, ncol=ncol(m)), diag=FALSE)
# place the text on the upper triagonal matrix
text(x=x[idx], y=y[idx], label=txt[idx], cex=0.8, xpd=TRUE)
# put similiar correlations together
plotCor(m, cluster=TRUE)
# same as
idx <- order.dendrogram(as.dendrogram(
hclust(dist(m), method = "mcquitty")
))
plotCor(m[idx, idx])
# plot only upper triangular matrix and move legend to bottom
m <- cor(mtcars)
m[lower.tri(m, diag=TRUE)] <- NA
# get the p-values
p <- outer(
(vars <- colnames(mtcars)), vars,
Vectorize(function(v1, v2)
cor.test(mtcars[[v1]], mtcars[[v2]], method = "pearson")$p.value
)
)
dimnames(p) <- list(vars, vars)
m[p > 0.05] <- NA
plotCor(m, mar=c(8,8,8,8), yaxt="n",
legend = list(x="bottom", inset=-.15, horiz=TRUE,
height=abs(lineToUser(line = 2.5, side = 1)),
width=ncol(m)))
mtext(text = rev(rownames(m)), side = 4, at=1:ncol(m), las=1, line = -5, cex=0.8)
Grouped Density Plot
Description
Draws kernel density estimates for one or more groups. Supports both classical density plots and conditional density plots.
Usage
plotDens(x, ...)
## Default S3 method:
plotDens(
x,
...,
main = NULL,
xlab = "",
ylab = "density",
xlim = NULL,
ylim = NULL,
bw = "nrd0",
add = FALSE,
col = NULL,
lwd = 2,
lty = 1,
fill = FALSE,
grid = NULL,
legend = TRUE,
stamp = .useTheme
)
## S3 method for class 'formula'
plotDens(
formula,
data,
subset,
na.action = na.omit,
main = NULL,
xlab = "",
ylab = NULL,
type = NULL,
...
)
Arguments
x |
A numeric vector or list of numeric vectors. |
... |
additional data vectors (unnamed, default method) or
graphical parameters passed to |
main |
main title. |
xlab, ylab |
axis labels. |
xlim, ylim |
axis limits. |
bw |
bandwidth passed to |
add |
logical; if |
col |
line color(s). |
lwd |
line width(s). |
lty |
line type(s). |
fill |
for |
grid |
logical, |
legend |
controls the legend, drawn only for more than one curve,
with the group names (the level names for the formula method, the
names of the data arguments otherwise). |
stamp |
controls the corner stamp. |
formula |
a formula of the form |
data |
an optional data frame containing the variables in the formula. |
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled,
defaults to |
type |
character string specifying the plot type. One of
|
Details
The function defers entirely to bedrock::resolveFormula()'s
design classification to pick a mode when type = NULL:
-
y ~ g(gcategorical) → density, one curve per group. -
y ~ x(xnumeric) → conditional densityP(Y | X), a single curve - equivalent tocdplot(x, factor(y)). -
y ~ x | g→ conditional density, one curve per level ofg.
type can be set explicitly to override the default for a given
design (e.g. to force an error rather than silently doing the wrong
thing if a formula's shape is ambiguous).
Graphical elements such as grids are controlled via the unified plot
design system using bedrock::callIf() and .theme().
Value
Invisibly returns NULL.
See Also
stats::density(), graphics::cdplot(),
bedrock::resolveFormula()
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
set.seed(1)
x <- rnorm(100)
g <- rep(c("A", "B"), each = 50)
# standard density (k = 2 groups)
plotDens(x ~ g)
# conditional density, single curve - auto-detected, no type= needed
y <- rbinom(100, 1, plogis(x))
plotDens(y ~ x)
# same, with cdplot-style fill
plotDens(y ~ x, fill = c("red", "blue"))
# conditional density, stratified by group
plotDens(y ~ x | g)
# subset and the cells of two grouping variables
plotDens(len ~ supp:dose, ToothGrowth, subset = dose > 0.5)
Two-Dimensional Kernel Density Plot
Description
Computes a two-dimensional kernel density estimate and visualises it using contour, image, or perspective plots.
Usage
plotDens2D(
x,
y,
main = NULL,
xlab = NULL,
ylab = NULL,
xlim = NULL,
ylim = NULL,
type = c("contour", "image", "persp"),
col = rev(pal("red-black", n = 100)),
grid = .useTheme,
box = .useTheme,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector of x-coordinates. |
y |
numeric vector of y-coordinates. Must have the same length as |
main |
optional main title of the plot. |
xlab, ylab |
axis labels. |
xlim, ylim |
numeric vectors of length two specifying axis limits. |
type |
character string specifying the plot type.
One of |
col |
color specification used for |
grid |
controls drawing of the background grid. |
box |
controls drawing of the plot box. |
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to underlying plotting functions. |
Details
The function estimates a bivariate density surface using a Gaussian kernel with bandwidths determined via a normal reference rule. The density is evaluated on a regular grid and visualised using one of three base graphics representations:
-
"contour": contour lines of equal density -
"image": raster representation of the density surface -
"persp": three-dimensional perspective plot
The choice of representation affects interpretability: contour and image plots emphasise structure in the data distribution, while perspective plots highlight global shape but may distort local density.
Bandwidth selection follows a rule-of-thumb approach based on spread (interquartile range and variance), which provides a reasonable default for unimodal distributions but may oversmooth multimodal structures.
Missing or non-finite values are not allowed and will result in an error.
Value
Invisibly returns the result of the selected plotting call. Typically a list containing grid coordinates and estimated density values.
See Also
Other plot.bivariate:
plotAssoc(),
plotBag(),
plotBubble(),
plotCor(),
plotHeatmap(),
plotHexbin(),
plotMosaic(),
plotXY()
Examples
set.seed(1)
x <- rnorm(200)
y <- x + rnorm(200)
plotDens2D(x, y)
plotDens2D(x, y, type = "image")
Density and Boxplot Combination (Grouped)
Description
Combines density plots and horizontal boxplots for a numeric variable, optionally grouped by a categorical variable. The density plot shows the distribution shape, while the boxplot summarizes key statistics such as median, spread, and outliers.
Usage
plotDensBox(x, ...)
## Default S3 method:
plotDensBox(
x,
groups = NULL,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
heights = c(2, 1.4),
col = NULL,
grid = TRUE,
dens = TRUE,
box = TRUE,
stamp = .useTheme,
...
)
## S3 method for class 'formula'
plotDensBox(
formula,
data,
subset,
na.action = na.omit,
main = NULL,
xlab = "",
...
)
Arguments
x |
numeric vector, or a formula of the form |
... |
further graphical parameters passed to
|
groups |
optional grouping variable (ignored if a formula is used). |
main |
main title. |
xlab |
label for the x-axis, drawn below the boxplot. For the formula method, an empty label defaults to the response. |
ylab |
label for the y-axis of the density panel. |
xlim |
numeric vector of length 2 specifying the x-axis limits.
|
heights |
numeric vector of length 2 specifying the relative heights of the density plot (top) and boxplot (bottom). |
col |
vector of colors, recycled over the groups. If |
grid |
controls drawing of the background grid. Can be:
|
dens |
controls density estimation via
|
box |
controls drawing of boxplots via
|
stamp |
controls the corner stamp. |
formula |
a formula of the form |
data |
an optional data frame containing the variables in the formula. |
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled,
defaults to |
Details
The function arranges two plots vertically using layout():
a density plot on top and a horizontal boxplot below. When a grouping
variable is provided, densities and boxplots are drawn for each group.
Optional plot components are controlled using
bedrock::callIf() semantics:
-
TRUE: draw with defaults -
FALSE: suppress component named list: customize component arguments
Value
Invisibly returns NULL.
See Also
stats::density(),
graphics::boxplot(),
bedrock::callIf()
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
set.seed(1)
x <- rnorm(100)
g <- sample(c("A", "B"), 100, TRUE)
plotDensBox(x)
plotDensBox(x, g)
plotDensBox(
x,
dens = list(adjust = 2),
box = list(notch = TRUE)
)
plotDensBox(
x,
box = FALSE
)
plotDensBox(x ~ g)
# subset and the cells of two grouping variables
plotDensBox(len ~ supp:dose, ToothGrowth, subset = dose > 0.5)
Dot Plot for Estimates and Confidence Intervals
Description
Displays numeric estimates as points on a horizontal scale. Optional confidence limits are shown as horizontal lines with capped endpoints. Several series of estimates can be arranged in labelled groups.
Usage
plotDot(
x,
main = NULL,
xlim = NULL,
xax = NULL,
axes = TRUE,
items = NULL,
groups = NULL,
gap = 1,
pch = .useTheme,
cex = .useTheme,
grid = .useTheme,
box = .useTheme,
stamp = .useTheme,
...
)
Arguments
x |
numeric estimates or confidence interval data. Supported formats
are a numeric vector, a numeric matrix, a three-dimensional numeric array,
or a |
main |
main title. |
xlim |
numeric vector containing the limits of the horizontal axis; by default, the range of all estimates and confidence limits |
xax |
optional specification for the horizontal axis, interpreted by the internal axis renderer |
axes |
logical; whether the horizontal and item axes are drawn |
items |
optional character vector containing the item labels; defaults
to the row names or first dimension names of |
groups |
optional character vector containing the group labels;
defaults to the column names or third dimension names of |
gap |
non-negative number, the vertical space between groups in item rows |
pch |
specification for the estimate points. The default
|
cex |
character expansion factor for the points. |
grid |
specification controlling the horizontal item and group grid
lines. The default |
box |
specification controlling the plot box. The default
|
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to
|
Details
A numeric vector represents one estimate for each item; a
one-dimensional table or array, such as the result of tapply() with
one grouping factor, is treated the same way.
A numeric matrix represents estimates only: rows define the items and columns define the groups. Consequently, a matrix with three columns is interpreted as three groups and not automatically as estimates with lower and upper confidence limits.
Use as.CI() to declare explicitly that a matrix, data frame,
list, or result from tapply() contains confidence interval
data:
plotDot(as.CI(x))
A "CI" object contains the columns est, lci, and
uci. Additional columns can define the item and group structure.
If two additional columns are present, the first defines the items and the
second defines the groups.
Confidence interval data can alternatively be supplied as a
three-dimensional numeric array with dimensions
items × 3 × groups. The second dimension must contain, in this
order, the estimate, lower confidence limit, and upper confidence limit.
Values supplied directly as arguments take precedence over the
corresponding settings of the active theme. Vectors in pch (e.g.
pch = list(col = c("red", "blue"))) are recycled over the groups, in
the order in which the groups are drawn from top to bottom.
Value
invisibly, a list containing:
yposvertical positions of the items within each group, a list in the order of the groups
group_yvertical positions of the group labels
sep_yvertical positions of the group separators
See Also
as.CI(), isCI(),
graphics::dotchart()
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
# estimates for a single series
est <- c(A = 12, B = 18, C = 28, D = 40, E = 65)
plotDot(
est,
main = "Estimates"
)
# matrix columns represent groups of estimates
groupedEst <- cbind(
Control = c(A = 12, B = 18, C = 28),
Treatment = c(A = 16, B = 24, C = 35)
)
plotDot(
groupedEst,
main = "Grouped estimates"
)
# confidence intervals stored in a matrix
ci <- cbind(
est = est,
lci = est - c(2, 3, 4, 5, 6),
uci = est + c(2, 3, 4, 5, 6)
)
plotDot(
as.CI(ci),
main = "Estimates with confidence intervals"
)
# grouped confidence intervals stored in a data frame
groupedCI <- data.frame(
item = rep(c("A", "B", "C"), 2),
group = rep(c("Control", "Treatment"), each = 3),
estimate = c(12, 18, 28, 16, 24, 35),
lower = c(10, 15, 24, 13, 20, 30),
upper = c(14, 21, 32, 19, 28, 40)
)
plotDot(
as.CI(
groupedCI,
estimate = "estimate",
lower = "lower",
upper = "upper"
),
main = "Grouped confidence intervals"
)
# returned positions can be used to add graphical elements
pos <- plotDot(est)
points(
est + 3,
y = unlist(pos$ypos),
pch = 4
)
Empirical Cumulative Distribution Function
Description
Fast plotting of the empirical cumulative distribution function (ECDF), designed to stay performant even for very large vectors (n ~ 1e6-1e7).
Usage
plotECDF(x, ...)
## Default S3 method:
plotECDF(
x,
main = NULL,
xlab = NULL,
ylab = "",
xlim = NULL,
breaks = 1000,
add = FALSE,
col = .useTheme,
lwd = 2,
grid = .useTheme,
box = .useTheme,
stamp = .useTheme,
...
)
## S3 method for class 'formula'
plotECDF(
formula,
data,
subset,
na.action = na.omit,
main = NULL,
xlab = NULL,
xlim = NULL,
col = .useTheme,
lwd = 2,
legend = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector of the observations for the ECDF. Missing values are removed. |
... |
further graphical parameters passed to |
main |
main title. |
xlab |
label for the x-axis. |
ylab |
label for the y-axis. The y-axis itself always shows fixed
probability labels ( |
xlim |
numeric vector of length 2; x-axis limits. |
breaks |
controls the rendered resolution. A single integer (default
|
add |
logical; if |
col |
color of the step line and the min/max marker points.
|
lwd |
line width. |
grid |
controls drawing of the background grid (vertical lines at
default tick positions, plus a fixed set of horizontal reference
lines at the probability ticks
|
box |
controls drawing of the plot box. |
stamp |
controls the corner stamp. |
formula |
a formula of the form |
data |
an optional data frame containing the variables in the formula. |
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled.
Defaults to |
legend |
controls the legend of the formula method, drawn with the
group levels. |
Details
The base plot.ecdf()/ecdf() machinery becomes
impractically slow well below n = 1e7, since it tracks every single
jump. Beyond a few thousand points, individual jumps are visually
indistinguishable anyway, so plotECDF() caps the rendered resolution
at breaks points by default.
Resolution is achieved via quantile subsampling, not histogram binning:
breaks evenly-spaced probability points are mapped back to their
corresponding quantiles (stats::quantile(), type = 7).
Each rendered point therefore lies exactly on the true ECDF - unlike an
equal-width-histogram approximation, this adapts automatically to the
shape of the distribution (no resolution is wasted on near-empty bins in
a skewed or heavy-tailed distribution, nor lost in the tails).
Value
Invisibly returns NULL.
See Also
plot.ecdf(), plotFreqDist(),
theme
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
plotECDF(faithful$eruptions)
# large vector - automatically thinned to 1000 points, no breaks= needed
x <- rnorm(1e6)
plotECDF(x)
# force full resolution regardless of size
plotECDF(x, breaks = NULL)
# grouped ECDFs via the formula interface
plotECDF(Sepal.Length ~ Species, data = iris)
# subset and the cells of two grouping variables
plotECDF(len ~ supp:dose, ToothGrowth, subset = dose > 0.5)
Facet Panel Matrix in Base Graphics
Description
Draws a lattice-like matrix of panels in base graphics with identical plot region sizes, panel strips, axes on the outer panels only and a user-supplied panel function for the content. Panel gaps are defined in margin lines and remain exact, independent of device size and strip height, as the strip space is reserved separately in the layout.
Usage
plotFacet(
samples,
dim,
FUN,
main = "",
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
horiz = 1,
vert = NULL,
col = NULL,
bg = "grey95",
strip = TRUE,
grid = TRUE,
stamp = .useTheme,
...
)
Arguments
samples |
a list of samples, each a list (or data.frame) with
components |
dim |
integer vector of length 2, the number of rows and columns
of the panel matrix, |
FUN |
the panel function, called per panel as
|
main |
the main title, placed in the outer margin. |
xlab, ylab |
the axis labels, placed in the outer margins. |
xlim, ylim |
the axis limits. A numeric vector of length 2 (or
|
horiz |
the horizontal gap between adjacent columns in margin lines. |
vert |
the vertical gap between adjacent rows in margin lines.
Default is |
col |
the colors for the panels, recycled to the number of
samples. Default is |
bg |
the background color of the plot regions. |
strip |
controls the panel strips: |
grid |
controls the grid lines, evaluated by bedrock::callIf:
|
stamp |
controls the corner stamp. |
... |
further arguments passed to |
Details
The available device area inside the outer margins is partitioned with
layout() such that all plot regions have exactly the same
size in inches. The horizontal gap between two adjacent columns is
horiz margin lines, the vertical gap between two adjacent rows is
vert lines. Since margin lines have the same physical size in
both directions, horiz == vert yields visually equal gaps.
Value
Invisibly returns a list with the realized geometry:
horiz, vert, strip_line (reserved strip height
in lines) and the common plot region size plot_width_in,
plot_height_in in inches.
Bound and free scales
By default all panels share one coordinate system, and the axes are drawn on the outer panels only - the arrangement that makes small multiples comparable at a glance.
Passing xlim = "free" - or a list of limits, for control over
the individual panels - frees that dimension:
every panel gets its own limits, and with them its own axis, because an
outer axis would no longer describe the panels above or beside it.
The layout answers for this - a freed dimension reserves the full
mar on every panel edge that now carries annotation, not just on
the outer ones, so the panels stay equal in size and the tick labels
have room.
Free scales cost what they free: panels can no longer be compared by position, only by shape. The natural case is a set of diagnostics of one model against different predictors - the residual scale is shared and worth comparing, the predictor scales are not commensurable at all.
The strip is drawn with titleRect() above each panel. Its
height (line argument of titleRect) is reserved in the top
margin of every panel, so the strip never eats into the gap between the
rows.
Note that plot.new() silently reduces cex (and with
it csi, the physical size of a margin line) in layouts with more
than two regions, which would make the realized panel margins deviate
from the computed layout. The function therefore controls the character
size deterministically via cex (see ...) and sets the panel
margins in inches (mai/omi), so that all plot regions are
exactly equal in size.
See Also
graphics::layout, titleRect, bedrock::callIf
Other graphics.layout:
abcCoords(),
axTicksPosixct(),
axisBreak(),
isValidPlotRegion(),
lineToUser(),
mar(),
spreadOut()
Examples
samples <- lapply(split(ChickWeight, ChickWeight$Chick)[1:25],
function(z) list(x = z$Time, y = z$weight))
my_panel <- function(x, y, col, pch = 16, ...) {
points(x, y, pch = pch, col = col)
abline(lm(y ~ x), lwd = 1)
}
plotFacet(samples, dim = c(5, 5), FUN = my_panel,
xlab = "Time", ylab = "Weight", main = "ChickWeight",
strip = list(bg = "grey80", cex = 0.8))
# free x scales: mpg against four predictors, each on its own range,
# with a shared y scale. The regression band travels in the samples and
# reaches the panel function under its own names.
vars <- c("disp", "hp", "wt", "qsec")
samples <- lapply(vars, function(v) {
ord <- order(mtcars[[v]])
ci <- predict(lm(reformulate(v, "mpg"), mtcars), interval = "confidence")
list(x = mtcars[[v]][ord], y = mtcars$mpg[ord],
lci = ci[ord, "lwr"], uci = ci[ord, "upr"])
})
panelBand <- function(x, y, lci, uci, col, pch = 16, ...) {
polygon(c(x, rev(x)), c(uci, rev(lci)), col = "grey85", border = NA)
points(x, y, col = col, pch = pch)
}
plotFacet(setNames(samples, vars), dim = c(2, 2), FUN = panelBand,
xlim = "free", ylab = "mpg",
main = "mpg against four predictors")
Frequency Distribution Plot
Description
Creates a univariate graphical summary combining a histogram (or probability mass plot for discrete data), a kernel density curve, a boxplot, and an empirical cumulative distribution function in a single multi-panel figure. Optional components include a rug, and fitted theoretical distribution curves for both the histogram and the ECDF panel.
Usage
plotFreqDist(
x,
main = NULL,
xlab = "",
xlim = NULL,
heights = NULL,
hist = TRUE,
dens = TRUE,
rug = FALSE,
curve = FALSE,
boxplot = TRUE,
ecdf = TRUE,
curveEcdf = FALSE,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector whose distribution is to be plotted. |
main |
main title. |
xlab |
label for the x-axis. The variable name is typically placed
in |
xlim |
range of the x-axis. |
heights |
numeric vector of relative panel heights for
|
hist |
controls the histogram panel. |
dens |
controls the kernel density curve. |
rug |
controls a rug plot. |
curve |
controls a fitted theoretical distribution curve on the
histogram. |
boxplot |
controls the boxplot panel. |
ecdf |
controls the ECDF panel. |
curveEcdf |
controls a fitted theoretical CDF curve on the ECDF
panel, analogous to |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to |
Details
Each plot component is controlled via a single argument accepting
bedrock::callIf() semantics:
-
TRUE: draw with package defaults -
FALSE,NULL, orNA: suppress entirely a named list: draw with the given overrides merged into the defaults
Performance: for very large vectors (n > 1e7) the density curve, ECDF,
and semi-transparent boxplot outliers will still take noticeable time.
For exploratory work on very large data, consider sampling first:
plotFreqDist(x[sample(length(x), 5000)]).
Value
No return value (invisible NULL), called for its side effect of
drawing the plot.
See Also
hist(), boxplot(), plotECDF(),
density(), rug(), layout(),
theme
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotLines(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
plotFreqDist(faithful$eruptions)
# custom histogram breaks, density color, boxplot styling
plotFreqDist(faithful$eruptions,
hist = list(breaks = 50),
dens = list(col = "olivedrab4"),
boxplot = list(col = "olivedrab2", pch.mean = NA, col.meanci = NA))
# no density, no ecdf, add rug instead
plotFreqDist(faithful$eruptions,
dens = FALSE, ecdf = FALSE,
hist = list(xaxt = "s"),
rug = TRUE,
heights = c(3, 2.5),
main = "Eruption time")
# overlay a normal density curve
x <- rnorm(1000)
plotFreqDist(x, curve = TRUE, boxplot = FALSE, ecdf = FALSE)
# compare with a t-distribution curve
plotFreqDist(x,
curve = list(expr = ~ dt(x, df = 2), col = "darkgreen"),
boxplot = FALSE, ecdf = FALSE)
# overlay gamma distribution on both histogram and ECDF
ozone <- airquality$Ozone
m <- mean(ozone, na.rm = TRUE)
v <- var(ozone, na.rm = TRUE)
plotFreqDist(ozone,
hist = list(breaks = 15),
curve = list(expr = ~ dgamma(x, shape = m^2/v, scale = v/m),
col = "navajowhite3"),
curveEcdf = list(expr = ~ pgamma(x, shape = m^2/v, scale = v/m),
col = "navajowhite3"),
main = "Airquality - Ozone")
Plot Mathematical Functions
Description
Flexible plotting of mathematical functions in Cartesian, polar, and parametric form.
Usage
plotFun(
expr,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
from = 0,
to = 1,
n = 500,
args = NULL,
add = FALSE,
col = .useTheme,
lwd = 1,
lty = 1,
grid = .useTheme,
stamp = .useTheme,
...
)
Arguments
expr |
expression defining the function. Either a formula
( |
main |
main title. |
xlab, ylab |
labels for the axes. |
xlim, ylim |
numeric vectors of length 2 defining axis limits.
For Cartesian functions, |
from, to |
numeric; lower and upper bound of the parameter domain.
Default |
n |
integer; number of evaluation points. Default |
args |
named list of additional parameters fixed for the function
expression (e.g. |
add |
logical; if |
col |
color of the line. |
lwd |
line width. Default |
lty |
line type. Default |
grid |
controls drawing of the background grid. |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to
|
Details
The function automatically detects the type of input:
-
Cartesian:
y ~ f(x) -
Polar:
r ~ f(phi)orr ~ f(theta) -
Parametric:
list(x ~ f(t), y ~ g(t))
Additional parameters fixed for the expression can be passed via
args.
Value
Invisibly returns a list with components x and y
(the plotted coordinates after finite filtering).
See Also
Other plot.distribution:
plotProbDist(),
shade()
Examples
# Cartesian
plotFun(y ~ x^2)
# Damped oscillation - add second curve to existing plot
plotFun(y ~ 3*exp(-x/5)*sin(4*x), from = 0, to = 10)
plotFun(y ~ 3*exp(-x/5)*sin(6*x), from = 0, to = 10, add = TRUE)
# Cardioid (polar)
plotFun(r ~ 2*(1 + cos(phi)), from = 0, to = 2*pi)
# Heart curve (parametric)
plotFun(
list(
x ~ 13*cos(t) - 5*cos(2*t) - 2*cos(3*t) - cos(4*t),
y ~ 16*sin(t)^3
),
from = 0, to = 2*pi, lwd = 2
)
# Parameter sweep
for (a in 1:3)
plotFun(y ~ sin(a*x), args = list(a = a),
from = 0, to = 2*pi,
add = (a != 1), col = a)
Heatmap for Categorical Data
Description
Visualizes a contingency table using a heatmap representation. Cell values are mapped to colors based on counts or proportions, optionally with text labels overlaid.
Usage
plotHeatmap(
x,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
zlim = NULL,
scale = c("count", "prop", "row", "col"),
col = .useTheme,
border = NA,
naCol = "gray90",
box = .useTheme,
text = FALSE,
stamp = .useTheme,
...
)
Arguments
x |
a contingency table, matrix, or a pair of categorical vectors
coercible via |
main |
main title. |
xlab |
label for the x-axis. |
ylab |
label for the y-axis. |
xlim, ylim |
numeric vectors of length 2 specifying axis limits. |
zlim |
numeric vector of length 2 specifying the range used for
color scaling. If |
scale |
character specifying how values are computed:
|
col |
optional vector of colors. Default is a hardcoded sequential
white-to-navy ramp ( |
border |
color of tile borders. Defaults to |
naCol |
color used for missing values. |
box |
controls drawing of the outer frame around the tile grid,
drawn via |
text |
logical; if |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to
|
Details
The heatmap represents values in a contingency table using color intensity.
Depending on scale, the plot shows either absolute counts or different
types of proportions. Rows are drawn in reading order: the first table row
appears at the top, matching the printed table and the other bivariate
plots. This plot complements association and spine plots by
focusing on overall structure rather than conditional distributions or
statistical inference.
Value
Invisibly returns the matrix used for plotting.
See Also
plotAssoc(), graphics::image(),
theme
Other plot.bivariate:
plotAssoc(),
plotBag(),
plotBubble(),
plotCor(),
plotDens2D(),
plotHexbin(),
plotMosaic(),
plotXY()
Examples
# applicants by department and gender
tab <- margin.table(UCBAdmissions, c(3, 2))
plotHeatmap(tab,
scale = "prop",
text = TRUE)
# share of the genders within the departments
plotHeatmap(tab,
scale = "row",
text = TRUE,
main = "Applicants by department")
Hexagonal Binning Plot
Description
Displays a two-dimensional density estimate using hexagonal bins. Observations are aggregated into hexagons and coloured according to the number of observations falling into each cell.
Usage
plotHexbin(
x,
y,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
nBins = 30,
col = NULL,
border = NA,
grid = .useTheme,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector of x-values. |
y |
numeric vector of y-values. |
main |
main title. |
xlab |
label for the x-axis. |
ylab |
label for the y-axis. |
xlim |
limits for the x-axis. |
ylim |
limits for the y-axis. |
nBins |
number of hexagons across the x-axis. |
col |
colours used for the count scale. If |
border |
border colour of the hexagons. |
grid |
controls the background grid. |
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to
|
Value
Invisibly returns a list containing the computed
hexbin object and the original x and y.
See Also
Other plot.bivariate:
plotAssoc(),
plotBag(),
plotBubble(),
plotCor(),
plotDens2D(),
plotHeatmap(),
plotMosaic(),
plotXY()
Examples
if (requireNamespace("hexbin", quietly = TRUE)) {
set.seed(42)
x <- rnorm(5000)
y <- x + rnorm(5000)
plotHexbin(x, y)
# fewer and larger cells, user-defined colors
plotHexbin(x, y, nBins = 15,
col = hcl.colors(50, "YlOrRd", rev = TRUE), border = "white",
main = "Hexagonal binning")
}
Lift Chart
Description
Draws the cumulative lift curve, the cumulative gain curve, or the per-group lift bars of a binary classifier, together with the baseline of a random model. The chart answers the operational question directly: how much better is acting on the top-scored share of the cases than acting on a random share of the same size.
Usage
plotLift(
x,
main = NULL,
xlab = NULL,
ylab = NULL,
ylim = NULL,
type = c("cumulative", "gain", "decile"),
col = .useTheme,
lwd = 2,
grid = .useTheme,
box = .useTheme,
baseline = TRUE,
perfect = FALSE,
legend = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
an object of class |
main |
main title. |
xlab |
label for the x-axis. |
ylab |
label for the y-axis. |
ylim |
numeric vector of length 2; y-axis limits. |
type |
the curve to draw. One of |
col |
color of the curve or the bars. |
lwd |
line width of the curve. Has no effect for
|
grid |
controls drawing of the background grid. Can be:
|
box |
controls drawing of the plot box. |
baseline |
controls the reference line of a random model - a
horizontal line at 1 for
|
perfect |
controls the curve of a perfect ranking - the theoretical
maximum attainable at each depth, given the base rate. |
legend |
controls drawing of the legend. Can be:
|
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to |
Details
Reading the cumulative curve at depth 0.2 gives the factor by which contacting the top-scored fifth of the cases beats contacting a random fifth. The gain variant answers the complementary question - what share of all positives that fifth captures.
The curve necessarily converges to 1 (cumulative lift) or to the diagonal endpoint (gain) at depth 1, where all cases are selected and the model no longer discriminates. Only the left part of the curve carries decision value: a model that separates well over the first two deciles and poorly afterwards is preferable for a small campaign to one with the reverse profile and identical AUC.
Optional plot components (grid, box, baseline,
perfect, legend) follow bedrock::callIf()
semantics:
-
TRUE: draw with defaults -
FALSE,NULL, orNA: suppress component named list: customize component arguments
col, grid, box, and stamp default to
.useTheme, deferring to the package's active theme (see theme)
rather than a hardcoded value.
The number of groups is a property of the lift table, not of the plot -
set it via the nBins argument of alloy::lift().
Value
Invisibly returns x.
See Also
alloy::lift(), alloy::roc(), plotECDF(),
bedrock::callIf(), theme
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
# A lift table is normally computed by alloy::lift(). To keep the example
# self-contained, the columns used by the plot are built by hand here:
# cases ranked by decreasing score and cut into equally sized groups.
liftTable <- function(score, y, nBins = 10) {
y <- y[order(score, decreasing = TRUE)]
bin <- cut(seq_along(y), nBins, labels = FALSE)
nObs <- as.vector(table(bin))
nPos <- as.vector(tapply(y, bin, sum))
structure(
data.frame(bin = seq_len(nBins),
lift = (nPos / nObs) / mean(y),
depth = cumsum(nObs) / length(y),
cumLift = (cumsum(nPos) / cumsum(nObs)) / mean(y),
gain = cumsum(nPos) / sum(y)),
class = c("Lift", "data.frame"),
baseRate = mean(y))
}
y <- as.integer(iris$Species == "virginica")
fit <- glm(y ~ Sepal.Length + Sepal.Width, data = iris, family = binomial)
lft <- liftTable(fitted(fit), y)
plotLift(lft)
plotLift(lft, type = "gain")
# Per-group bars, coarser grouping set at computation time
plotLift(liftTable(fitted(fit), y, nBins = 5), type = "decile")
# Add the perfect-ranking reference, suppress the legend
plotLift(lft, perfect = TRUE, legend = FALSE)
# No title, compact top margin
plotLift(lft, main = "")
Line Plot for Multiple Series
Description
Draws one or several line series using graphics::matplot().
The function accepts either a matrix of values or separate x and
y coordinates and supports optional point symbols, grid lines,
and an automatically positioned legend.
Usage
plotLines(
x,
y,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
xax = NULL,
yax = NULL,
lty = 1,
lwd = 2,
col = .useTheme,
points = FALSE,
grid = .useTheme,
legend = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector, matrix or data frame. If |
y |
optional numeric vector or matrix giving the y-values. If supplied,
|
main |
main title. |
xlab, ylab |
labels for the axes. |
xlim, ylim |
limits for the axes. |
xax, yax |
axis specification passed to |
lty |
line type(s). |
lwd |
line width(s). |
col |
colours for the lines. |
points |
controls drawing of points on the lines. |
grid |
controls drawing of the background grid. |
legend |
controls the legend. |
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to |
Details
If y is missing, x is interpreted as a matrix and each column
is drawn as a separate line. Row names are used for the x-axis labels if
available. The legend labels default to the column names of the data.
Value
Invisibly returns a list containing:
-
xthe x-values used for plotting, -
ythe y-values (if supplied), -
legendthe legend specification if drawn.
See Also
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotQQ(),
plotRidge(),
plotViolin()
Examples
m <- matrix(c(3,4,5,1,5,4,2,6,2), nrow = 3,
dimnames = list(
dose = c("A","B","C"),
age = c("2000","2001","2002")
))
plotLines(m, lwd = 2, main = "Dose ~ Age")
# with points
plotLines(m, points = TRUE)
# custom legend
plotLines(m, legend = list(cex = 0.8))
Plot Missing Data
Description
Takes a data frame and displays the location of missing data. The missings can be clustered and be displayed together.
Usage
plotMiss(
x,
main = NULL,
cluster = FALSE,
col = "deeppink4",
bg = fade("navajowhite3", 0.3),
stamp = .useTheme,
...
)
Arguments
x |
a data.frame to be analysed. |
main |
main title. |
cluster |
logical, defining if the missings should be clustered. Default
is |
col |
the colour of the missings. |
bg |
the background colour of the plot. |
stamp |
controls the corner stamp. |
... |
the dots are passed to |
Details
A graphical display of the position of the missings can be help to detect dependencies or patterns within the missings.
Value
if cluster is set to TRUE, the new order will be returned invisibly.
Note
Following an idea of Henk Harmsen henk@carbonmetrics.com
See Also
hclust(), bedrock::countCompCases()
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
plotMiss(airquality, main="Missing data (in orignal order)")
plotMiss(airquality, main="Missing data (clustered)", cluster=TRUE)
Mosaic Plot for 2-Way Contingency Tables
Description
Draws a mosaic plot (spine plot) for a 2-way contingency table, with proportional tile areas, optional cell labels (counts or percentages), and a "Few"-style minimal appearance (white tile separators, muted palette, optional legend).
Usage
plotMosaic(
x,
main = NULL,
xlab = NULL,
ylab = NULL,
swap = FALSE,
horiz = FALSE,
gap = 0.01,
col = .useTheme,
border = "white",
legend = TRUE,
labels = c("p", "n", "none"),
stamp = .useTheme,
...
)
Arguments
x |
a 2-way contingency table, matrix, or array coercible via
|
main |
main title. |
xlab, ylab |
character or |
swap |
logical. If |
horiz |
logical. If |
gap |
numeric. Width of the white separator drawn between adjacent
tiles, in plot-region units ( |
col |
vector of colors for the fill/legend variable (the second
table dimension, or first if |
border |
color of the tile borders. Default |
legend |
logical. Draw a legend for the fill variable.
Default |
labels |
character, one of |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to |
Details
Cells belonging to a row with a row total of zero are drawn as
zero-height tiles and receive no label, but do not cause an error or
NaN in the geometry.
In both orientations only the first table dimension receives an axis
(its split points are constant across the whole plot); the second
dimension's split points vary per column/row and are represented via
the legend only. No numeric probability axis is drawn. The second
dimension is stacked top-down (vertical) resp. left-to-right
(horiz = TRUE): its first level sits at the top / left, matching
graphics::spineplot() and the legend order.
Value
Invisibly, the data.frame of tile geometry as produced by
.computeMosaicTiles(), with columns x0, x1, y0, y1, n, p,
pCond and one column per table dimension. This allows users to add
further annotations (e.g. via rect() or text()) on top of the plot.
See Also
plotCatDist(), plotBar(), getTheme()
Other plot.bivariate:
plotAssoc(),
plotBag(),
plotBubble(),
plotCor(),
plotDens2D(),
plotHeatmap(),
plotHexbin(),
plotXY()
Examples
tab <- apply(HairEyeColor, c(1, 2), sum)
plotMosaic(tab)
plotMosaic(tab, swap = TRUE)
plotMosaic(tab, horiz = TRUE, main = "Hair ~ Eyecolor")
Polar Plot for Radial Data
Description
Creates a polar coordinate plot for one or multiple radial series.
Usage
plotPolar(
r,
theta = NULL,
main = NULL,
rlim = NULL,
type = "p",
add = FALSE,
col = NULL,
border = NULL,
stamp = .useTheme,
...
)
Arguments
r |
numeric vector or matrix of radial values. Each row represents one series. |
theta |
optional numeric vector or matrix of angles (in radians).
Must match the dimensions of |
main |
optional plot title. |
rlim |
numeric limit for radial axis. If |
type |
character vector specifying plot type for each series:
|
add |
logical; if |
col |
color for points/lines. |
border |
color for border in case of type |
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to base plotting functions. |
Details
The function supports plotting multiple radial series simultaneously.
Each row of r is treated as a separate series.
Angles are interpreted in radians. If theta is not provided,
points are distributed evenly over [0, 2\pi).
Graphical parameters such as lwd, lty, pch,
cex, fill, and mar can be passed via ....
Value
Invisibly returns NULL.
See Also
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotMiss(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
r <- matrix(runif(20), nrow = 2)
plotPolar(r, type = c("l", "p"), col = c("blue", "red"))
# with custom angles
theta <- seq(0, 2*pi, length.out = 10)
plotPolar(r[1,], theta = theta, type = "h")
Plot Probability Distribution
Description
Produces a plot of a probability distribution function with shaded areas. Useful for illustrating critical regions, p-values, or probability masses in statistics teaching materials.
Usage
plotProbDist(
breaks,
FUN,
main = NULL,
ylab = "density",
xlim = NULL,
col = NULL,
density = 7,
grid = .useTheme,
box = .useTheme,
areaLabels = NULL,
breakLabels = NULL,
stamp = .useTheme,
...
)
Arguments
breaks |
numeric vector of break points defining the boundaries between
shaded areas. The first and last value define the plot range passed to
|
FUN |
the distribution density function to plot, typically of the form
|
main |
main title. |
ylab |
label for the y-axis. Default is |
xlim |
numeric vector of length 2. x-axis limits passed to
|
col |
color(s) for the shaded areas. Recycled if shorter than the number of areas. Defaults to the "helsana" palette. |
density |
density of shading lines passed to |
grid |
controls the background grid. |
box |
controls the plot box. |
areaLabels |
controls labels placed in the centre of each shaded area.
|
breakLabels |
controls labels placed on the x-axis at interior break
points via |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to |
Value
NULL, invisibly.
See Also
Other plot.distribution:
plotFun(),
shade()
Examples
# Normal distribution with two areas
plotProbDist(breaks = c(-10, -1, 12),
FUN = function(x) dnorm(x, mean = 2, sd = 2),
main = "Normal-Distribution N(2,2)",
xlim = c(-7, 10),
col = c("deeppink4", "skyblue3"),
density = c(20, 7),
breakLabels = TRUE)
# t-distribution with three areas
plotProbDist(breaks = c(-6, -2.3, 1.5, 6),
FUN = function(x) dt(x, df = 8),
main = "t-Distribution (df=8)",
xlim = c(-4, 4),
col = c("deeppink4", "skyblue3", "darkorange2"),
density = c(20, 7),
areaLabels = FALSE,
breakLabels = list(text=c("A", "B")))
# Chi-square distribution
plotProbDist(breaks = c(0, 15, 35),
FUN = function(x) dchisq(x, df = 8),
main = expression(chi^2~"-Distribution (df=8)"),
xlim = c(0, 30),
col = c("deeppink4", "skyblue3"),
density = c(0, 20),
breakLabels = list(text="B"))
Plot Proportions with Confidence Intervals
Description
Displays a horizontal bar with nested confidence interval bands from
min(ciLevels) to max(ciLevels) to visualise the uncertainty
of a proportion. Bands are drawn in a semi-transparent grey so that the
accumulated overlap creates a natural density gradient - darker in the
centre, lighter at the edges.
Usage
plotPropCI(
x,
main = NULL,
xlab = "",
xlim = c(0, 1),
ciLevels = seq(0.99, 0.8, by = -0.01),
col = .useTheme,
ciCol = addOpacity("grey80", 0.12),
border = NA,
grid = .useTheme,
box = FALSE,
labels = c("", ""),
legend = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
A two-column integer matrix where each row represents a group and the two columns contain counts for the two categories. A numeric vector of length 2 is also accepted and will be coerced to a one-row matrix. |
main |
main title. |
xlab |
label for the x-axis. Default |
xlim |
numeric vector of length 2 for the x-axis limits.
Default |
ciLevels |
numeric vector of confidence levels for the nested bands.
Default |
col |
character vector of length 2 specifying fill colours for the
stacked bar. |
ciCol |
colour for the confidence interval bands. Default is a
semi-transparent grey ( |
border |
border colour for the confidence interval bands and the
stacked bar. Default |
grid |
controls drawing of the background grid (vertical lines at
the proportion ticks only - there is no meaningful horizontal grid
for the categorical group axis). |
box |
controls drawing of the plot box. Default |
labels |
character vector of length 2 with labels for the two
categories, displayed at the top of the plot. Default |
legend |
controls the legend explaining the CI band range.
|
stamp |
controls the corner stamp. |
... |
further arguments passed to |
Details
Each row of x is displayed as a horizontal stacked bar showing the
proportion of the first category. Confidence intervals are calculated
using prop.test() and drawn as nested bands per ciLevels,
all in the same semi-transparent colour. The repeated overdraw naturally
darkens the centre of the interval where all bands overlap. A vertical
segment marks the observed proportion.
Value
Invisibly returns NULL. Called for its side effect of
producing a plot.
See Also
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotMiss(),
plotPolar(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
m <- matrix(c(22, 111, 33, 120, 80, 100), nrow = 3, byrow = TRUE)
plotPropCI(m, labels = c("yes", "no"), main = "Response by Group")
# single row - vector input is accepted
plotPropCI(m[1, ], labels = c("yes", "no"))
QQ-Plot for Any Distribution
Description
Create a QQ-plot for a variable of any distribution. The assumed underlying distribution can be defined as a function of f(p), including all required parameters. Confidence bands are provided by default.
Usage
plotQQ(
x,
qFun = qnorm,
main = NULL,
xlab = NULL,
ylab = NULL,
datax = FALSE,
add = FALSE,
cex = .useTheme,
grid = .useTheme,
box = .useTheme,
cband = list(conf.level = 0.95),
qqline = TRUE,
stamp = .useTheme,
...
)
Arguments
x |
the data sample |
qFun |
the quantile function of the assumed distribution. Can either
be given as simple function name or defined as own function using the
required arguments. Default is |
main |
main title. |
xlab |
the xlab for the plot |
ylab |
the ylab for the plot |
datax |
logical. Should data values be on the x-axis? Default is
|
add |
logical specifying if the points should be added to an already
existing plot; defaults to |
cex |
character expansion factor for the points. |
grid |
controls drawing of the background grid. |
box |
controls drawing of the plot box. |
cband |
controls the confidence band. |
qqline |
arguments for the qqline. This will be estimated as a
line through the 25\
procedure as |
stamp |
controls the corner stamp. |
... |
the dots are passed to the plot function. |
Details
The function generates a sequence of points between 0 and 1 and transforms those into quantiles by means of the defined assumed distribution.
Value
No return value (invisible NULL), called for its side effect of
drawing the plot.
Note
The code is inspired by the tip 10.22 "Creating other
Quantile-Quantile plots" from R Cookbook and based on R-Core code from the
function qqline. The calculation of confidence bands are rewritten
based on an algorithm published in the package
BoutrosLab.plotting.general.
Based on code by Ying Wu
References
Teetor, P. (2011) R Cookbook. O'Reilly, pp. 254-255.
See Also
stats::qqnorm, stats::qqline, stats::qqplot, theme, lines.loess
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotRidge(),
plotViolin()
Examples
y <- rexp(100, 1/10)
plotQQ(y, function(p) qexp(p, rate=1/10))
w <- rweibull(100, shape=2)
plotQQ(w, qFun = function(p) qweibull(p, shape=4))
z <- rchisq(100, df=5)
plotQQ(z, function(p) qchisq(p, df=5),
qqline=list(col=2, probs=c(0.1, 0.6)),
main=expression("Q-Q plot for" ~~ {chi^2}[nu == 3]))
abline(0,1)
# 90% confidence band instead of the 95% default
plotQQ(y, function(p) qexp(p, rate=1/10), cband = list(conf.level = 0.90))
# add 5 random sets
for(i in 1:5){
z <- rchisq(100, df=5)
plotQQ(z, function(p) qchisq(p, df=5), add=TRUE, qqline = FALSE,
col="grey", lty="dotted")
}
Ridge Plot (Stacked Density Plot)
Description
Draws stacked kernel density estimates (ridge plot) for grouped data. Each group is displayed as a density curve shifted along the y-axis.
Usage
plotRidge(x, ...)
## Default S3 method:
plotRidge(
x,
...,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
bw = "nrd0",
normalize = c("global", "group"),
add = FALSE,
scale = 1,
spacing = 1,
col = NULL,
border = NULL,
lwd = 1,
lty = 1,
fill = TRUE,
grid = NA,
stamp = .useTheme
)
## S3 method for class 'formula'
plotRidge(
formula,
data,
subset,
na.action = na.omit,
main = NULL,
xlab = "",
ylab = "",
...
)
Arguments
x |
a numeric vector, or a list of numeric vectors representing groups. |
... |
further numeric vectors (unnamed), each forming a group, or
graphical parameters passed to |
main |
main title. |
xlab, ylab |
axis labels. For the formula method, empty labels default to the response and the grouping variable. |
xlim, ylim |
axis limits. |
bw |
bandwidth for |
normalize |
how the density heights are scaled to |
add |
logical; if |
scale |
scaling factor for density height. |
spacing |
vertical spacing between ridges. |
col |
fill color(s), recycled over the groups. |
border |
border color(s), recycled over the groups. |
lwd |
line width(s). |
lty |
line type(s). |
fill |
logical; fill area under densities. |
grid |
logical, |
stamp |
controls the corner stamp. |
formula |
a formula of the form |
data |
an optional data frame containing the variables in the formula. |
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled,
defaults to |
Details
Ridge plots are useful for comparing distributions across multiple groups. Each density is normalized and vertically offset, improving readability compared to overlaid density plots.
Value
Invisibly returns NULL.
See Also
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotViolin()
Examples
set.seed(1)
df <- data.frame(
value = c(rnorm(100), rnorm(100, 2), rnorm(100, 4)),
group = rep(c("A", "B", "C"), each = 100)
)
plotRidge(value ~ group, data = df)
# subset and the cells of two grouping variables
plotRidge(len ~ supp:dose, ToothGrowth, subset = len > 8)
# the narrow group VC:0.5 flattens all others; scale each ridge to its
# own peak instead
plotRidge(len ~ supp:dose, ToothGrowth, subset = len > 8,
normalize = "group")
Sankey Diagram (Flow Diagram)
Description
Draws a Sankey diagram: nodes arranged in stages (columns) and flows between them as ribbons whose width is proportional to their value, as used for money flows, patient pathways or energy balances. The input is a plain list of flows; stages, node order and colors are derived from it.
Usage
plotSankey(
x,
stages = NULL,
main = NULL,
order = NULL,
nodeWidth = 0.08,
gap = 0.03,
col = .useTheme,
border = NA,
flowCol = "source",
opacity = 0.4,
labels = TRUE,
values = FALSE,
stamp = .useTheme,
...
)
Arguments
x |
a data frame with one row per flow and three columns: the
origin node, the destination node and the value of the flow (finite,
non-negative). The column names do not matter, only their order. A
node may appear as destination in one stage and as origin in the
next. Node names identify nodes globally: a state that recurs at
different stages (e.g. "Healthy" before and after treatment) needs
distinct names, which |
stages |
optional character vector of column headings, one per
stage, e.g. |
main |
main title. |
order |
optional character vector of node names giving their
order from top to bottom within each stage. Nodes not listed follow
in the order of their first appearance in |
nodeWidth |
width of the nodes as a fraction of the distance between two stages, between 0 and 1. |
gap |
minimal vertical space between the nodes of a stage, as a fraction of the plot height (non-negative). It applies to the stage that needs the most room; the other stages spread their nodes over the same height, so all stages with more than one node are flush at the top and bottom. A stage with a single node is centred. |
col |
node colors. |
border |
color of a line along the left and right edge of the
nodes, where the ribbons meet them, e.g. |
flowCol |
color of the ribbons: |
opacity |
opacity of the ribbons, between 0 and 1. |
labels |
controls the node labels. |
values |
append the node value to the labels: |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to |
Details
The stage of a node is the length of the longest directed path that leads to it from a node without incoming flows, so the stages follow from the flows alone. Flows that lead back to an earlier node (cycles) are not supported. Zero flows are dropped, and with them nodes that have no other flows.
A flow may skip stages. It is then led through an invisible pass-through node in each stage in between, placed below the real nodes, so that it does not run through a node it has nothing to do with.
The height of a node is the larger of its total inflow and total
outflow; unequal totals are allowed. Within a node, the ribbons are
stacked in the order of the nodes they lead to or come from, which
avoids crossings at the node itself. The order of the nodes within a
stage is not optimised; order sets it by hand.
The left and right margins are widened for the labels of the first
and last stage, unless mar in ... sets those sides.
Value
Invisibly, a list with the data frames nodes (name, stage,
inflow, outflow, value = the larger of both, color and the
coordinates of each node) and flows (the positive flows with their
vertical positions at both ends), e.g. for checking balances or
adding annotations.
See Also
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotTernary(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
# Financing of the Swiss health care system (simplified, CHF bn):
# one row per flow - origin, destination, value
flows <- data.frame(
from = c("Confederation", "Confederation", "Cantons", "Cantons",
"Municipalities", "Companies", "Companies",
"Households", "Households", "Households",
"State", "State", "Health insurance", "Health insurance",
"Social insurance", "Social insurance",
"Private insurance", "Private insurance",
"Out-of-pocket", "Out-of-pocket"),
to = c("State", "Health insurance", "State", "Health insurance",
"State", "Health insurance", "Social insurance",
"Health insurance", "Private insurance", "Out-of-pocket",
"Hospitals", "Nursing homes", "Hospitals", "Physicians",
"Hospitals", "Nursing homes", "Hospitals", "Physicians",
"Physicians", "Dentists"),
value = c(5, 2, 9, 2, 4, 7, 2, 18, 8, 12,
12, 6, 14, 15, 2, 3, 4, 4, 7, 5)
)
plotSankey(flows, stages = c("Sources", "Financing", "Providers"))
# own colors for some nodes, ribbons colored by destination, values
plotSankey(flows, col = c(Households = "darkgreen", State = "orange"),
flowCol = "target", values = TRUE, border = "white", lwd = 2)
# a flow that skips a stage is led around the nodes in between
plotSankey(data.frame(from = c("A", "B", "A"), to = c("B", "C", "C"),
value = c(5, 5, 3)))
# the same state at two stages: distinct names, same label
path <- data.frame(from = c("Healthy.1", "Healthy.1", "Ill", "Ill"),
to = c("Healthy.2", "Ill", "Healthy.2", "Dead"),
value = c(70, 30, 20, 10))
plotSankey(path, labels = c(Healthy.1 = "Healthy", Healthy.2 = "Healthy"))
Ternary Plot
Description
Draws a ternary plot for compositional data consisting of three non-negative components per observation. Each row is interpreted as a composition and internally rescaled to sum to 1 if necessary.
Usage
plotTernary(
x,
y = NULL,
z = NULL,
main = "",
xlim = c(-1, 1),
ylim = c(-0.5, 1),
add = FALSE,
col = NULL,
pch = 16,
cex = 1,
grid = NA,
labels = NULL,
stamp = .useTheme,
...
)
Arguments
x |
A numeric vector, matrix, or data frame. If |
y |
optional numeric vector for the second component. |
z |
optional numeric vector for the third component. |
main |
plot title. |
xlim, ylim |
plot limits (usually left at defaults). |
add |
logical; if |
col |
point color(s). |
pch |
plotting symbol. |
cex |
point size. |
grid |
logical, |
labels |
character vector of length 3 specifying axis labels. |
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to |
Details
A ternary plot represents three-part compositions on an equilateral triangle.
Each observation (x_1, x_2, x_3) is mapped to 2D coordinates using
barycentric transformation. If rows do not sum to 1, they are automatically
normalized with a warning.
Graphical elements such as grids are controlled via the unified plot
design system using bedrock::callIf() and .theme().
Value
Invisibly returns NULL.
See Also
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTimeSeries(),
plotTreemap(),
plotWeb()
Examples
set.seed(1)
x <- runif(100)
y <- runif(100)
z <- runif(100)
plotTernary(x, y, z)
# matrix input
M <- cbind(x, y, z)
plotTernary(M, labels = c("A", "B", "C"))
Combined Plot of a Time Series and Its ACF and PACF
Description
Combined plot of a time Series and its autocorrelation and partial autocorrelation
Usage
plotTimeSeries(
x,
main = NULL,
ylab = NULL,
maxLag = 10 * log10(length(x)),
stamp = .useTheme,
...
)
Arguments
x |
univariate time series. |
main |
an overall title for the plot |
ylab |
a title for the y axis: see |
maxLag |
integer. Defines the number of lags to be displayed. The default is 10 * log10(length(series)). |
stamp |
controls the corner stamp. |
... |
the dots are passed to the plot command. |
Details
plotTimeSeries plots a combination of the time series and its autocorrelation and partial autocorrelation.
Value
x, invisibly. Called for its side effect of drawing the plot.
Note
Rewritten based on ideas of M.Huerzeler
See Also
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTreemap(),
plotWeb()
Examples
plotTimeSeries(AirPassengers)
Treemap Plot
Description
Draws a treemap in which the area of each rectangle is proportional to the
corresponding value in x. Optionally, rectangles can be grouped into
higher-level regions.
Usage
plotTreemap(
x,
groups = NULL,
main = NULL,
area = NULL,
labels = NULL,
stamp = .useTheme,
...
)
Arguments
x |
numeric vector of positive values determining the rectangle sizes. |
groups |
optional grouping variable. Values sharing the same group are
placed within a common enclosing region. A list sets the appearance
of the group regions as well: it holds the grouping variable (element
|
main |
main title of the plot. |
area |
controls the appearance of individual rectangles.
|
labels |
controls the labels of individual rectangles.
|
stamp |
controls the corner stamp. |
... |
additional graphical parameters passed to
|
Details
The appearance of individual rectangles is controlled through the
area and labels arguments, that of the groups through the elements
area and labels of a groups list. These accept logical values,
vectors, or lists.
Individual rectangles are sized according to the values in x. When
groups is supplied, a treemap is first constructed for the groups,
and each group's area is then subdivided among its members.
The arguments area and labels - and their counterparts in a
groups list - provide a flexible interface for controlling the
appearance of the plot while keeping the main function signature compact.
Value
Invisibly returns a list containing the coordinates of group centres and the centres of their child rectangles.
See Also
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotWeb()
Examples
x <- c(A = 6, B = 5, C = 4, D = 3, E = 2, F = 1)
plotTreemap(x)
plotTreemap(
x,
labels = list(col = "white")
)
grp <- c("G1", "G1", "G1", "G2", "G2", "G2")
plotTreemap(
x,
groups = list(grp, labels = TRUE)
)
plotTreemap(
x,
groups = list(grp, area = list(border = "black", lwd = 2)),
area = terrain.colors(length(x)),
labels = FALSE
)
Violin Plot
Description
Draws violin plots for one or more groups, combining kernel density estimation with optional boxplot overlays. The function follows a boxplot-like interface and supports both default and formula methods.
Usage
plotViolin(x, ...)
## Default S3 method:
plotViolin(
x,
...,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
bw = "nrd0",
trim = TRUE,
horiz = FALSE,
at = NULL,
names = NULL,
add = FALSE,
col = "grey80",
border = "black",
lwd = 1,
grid = NA,
box = TRUE,
quantiles = NULL,
stamp = .useTheme
)
## S3 method for class 'formula'
plotViolin(
formula,
data,
subset,
na.action = na.omit,
main = NULL,
xlab = "",
ylab = "",
horiz = FALSE,
names = NULL,
...
)
Arguments
x |
numeric vector, list of numeric vectors, or first group. |
... |
additional data vectors (unnamed) or graphical parameters
passed to |
main |
main title. |
xlab, ylab |
axis labels. For the formula method, empty labels default to the grouping variable and the response. |
xlim, ylim |
axis limits. |
bw |
bandwidth specification passed to |
trim |
logical. If |
horiz |
logical; if |
at |
numeric positions of the groups. |
names |
optional group labels. |
add |
logical; if |
col |
fill color(s) of the violins. |
border |
border color(s) of the violins. |
lwd |
line width for violin borders. |
grid |
logical, |
box |
logical or list controlling the boxplot overlay (see Details). |
quantiles |
optional numeric vector of probabilities for drawing quantile lines inside each violin. |
stamp |
controls the corner stamp. |
formula |
a formula of the form |
data |
an optional data frame containing the variables in the formula. |
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled,
defaults to |
Details
The violin shape is constructed from a kernel density estimate of each group, scaled to a fixed maximum width. Optionally, boxplots and quantile lines can be added.
Graphical elements such as the boxplot overlay and grid are controlled
via a flexible interface using TRUE, FALSE, NA, or
list(...) and are evaluated using bedrock::callIf().
Value
Invisibly returns NULL.
Data Handling
The function accepts:
a numeric vector
multiple vectors via
...a list of numeric vectors
Groups are handled similarly to boxplot().
See Also
Other plot.univariate:
plotArea(),
plotBar(),
plotBox(),
plotCatDist(),
plotDens(),
plotDensBox(),
plotDot(),
plotECDF(),
plotFreqDist(),
plotLines(),
plotQQ(),
plotRidge()
Examples
set.seed(1)
x <- rnorm(100)
y <- rnorm(100, 1)
plotViolin(x, y)
# horizontal violins
plotViolin(x, y, horiz = TRUE)
# with quantiles
plotViolin(x, y, quantiles = c(0.25, 0.5, 0.75))
# untrimmed: tails extend beyond the observed data range
plotViolin(x, y, trim = FALSE)
# custom styling
plotViolin(x, y,
col = c("lightblue", "salmon"),
box = list(col = "white"),
grid = TRUE
)
# formula interface
df <- data.frame(
value = rnorm(200),
group = rep(letters[1:4], each = 50)
)
plotViolin(value ~ group, data = df)
# subset and the cells of two grouping variables
plotViolin(len ~ supp:dose, ToothGrowth, subset = len > 8)
Plot a Web of Connected Points
Description
Displays a symmetric matrix (typically a correlation matrix) as a network diagram: variables are placed equidistantly around a circle, and connecting lines between each pair are drawn with width proportional to the absolute value of the matrix entry and color indicating its sign.
Usage
plotWeb(
m,
main = NULL,
dist = 0.5,
col = hcol("red", "blue"),
lty = NULL,
lwd = NULL,
labels = TRUE,
points = list(pch = 21, cex = 2, col = "black", bg = "darkgrey"),
legend = TRUE,
stamp = .useTheme,
...
)
Arguments
m |
a symmetric numeric matrix (e.g. a correlation matrix). |
main |
main title of the plot. |
dist |
distance of node labels from the outer circle. Default
|
col |
two colors for the connecting lines: the first is used for
negative values, the second for positive values. |
lty |
line type for the connecting lines. |
lwd |
line widths for the connecting lines. |
labels |
controls node labels around the circle.
|
points |
controls the node point symbols. The default
( |
legend |
controls the legend. |
stamp |
controls the corner stamp. |
... |
further graphical parameters passed to
|
Details
The function uses the lower triangular matrix of m; when
overriding lwd or col manually, values must be supplied in
the same order as m[lower.tri(m)].
Value
Invisibly returns a list of x/y coordinates of the
node points, useful for adding further annotations to the plot.
See Also
Other plot.special:
plotBinaryTree(),
plotCirc(),
plotLift(),
plotMiss(),
plotPolar(),
plotPropCI(),
plotSankey(),
plotTernary(),
plotTimeSeries(),
plotTreemap()
Examples
m <- cor(swiss)
plotWeb(m, main = "Swiss correlation")
# custom labels (abbreviations)
plotWeb(m, labels = list(abbreviate(colnames(m), 4), cex = 0.9))
# show only significant correlations
p <- outer(
(vars <- colnames(mtcars)), vars,
Vectorize(function(v1, v2)
cor.test(mtcars[[v1]], mtcars[[v2]])$p.value)
)
dimnames(p) <- list(vars, vars)
m2 <- cor(mtcars)
m2[p > 0.05] <- NA
plotWeb(m2, labels = list(las = 2))
Scatterplot with Optional Smooth Lines
Description
Draws a scatterplot of two numeric variables with optional linear and locally weighted regression lines, and an optional legend.
Usage
plotXY(x, ...)
## Default S3 method:
plotXY(
x,
y,
main = NULL,
xlab = "",
ylab = "",
xlim = NULL,
ylim = NULL,
col = .useTheme,
bg = .useTheme,
pch = .useTheme,
cex = .useTheme,
grid = .useTheme,
box = .useTheme,
lm = TRUE,
loess = TRUE,
legend = TRUE,
stamp = .useTheme,
...
)
## S3 method for class 'formula'
plotXY(
formula,
data,
subset,
na.action = na.omit,
main = NULL,
xlab = "",
ylab = "",
...
)
Arguments
x |
numeric vector of x-values, or a formula of the form |
... |
further graphical parameters passed to |
y |
numeric vector of y-values (ignored if a formula is used). |
main |
main title. |
xlab |
label for the x-axis. |
ylab |
label for the y-axis. |
xlim |
numeric vector of length 2; x-axis limits. If |
ylim |
numeric vector of length 2; y-axis limits. If |
col |
color of the points. |
bg |
background (fill) color of the points. |
pch |
plotting character. |
cex |
character expansion factor for points. |
grid |
controls drawing of the background grid. Can be:
|
box |
controls drawing of the plot box. Can be:
|
lm |
controls drawing of the linear regression line. Can be:
|
loess |
controls drawing of the locally weighted regression line. Can be:
|
legend |
controls drawing of the legend. Can be:
The legend is only drawn when at least one of |
stamp |
controls the corner stamp. |
formula |
a formula of the form |
data |
an optional data frame containing variables in the formula. |
subset |
an optional expression indicating which observations to
use, evaluated in |
na.action |
a function specifying how missing values are handled.
Defaults to |
Details
Optional plot components (grid, box, lm,
loess, legend) follow bedrock::callIf()
semantics:
-
TRUE: draw with defaults -
FALSE,NULL, orNA: suppress component named list: customize component arguments
col, bg, pch, cex, grid, and box
default to .useTheme, deferring to the package's active theme
(see theme) rather than a hardcoded value. This means
setTheme(list(points = list(col = "black"))) changes the point
color for every call to plotXY() (and any other function using
the same theme section) that doesn't override col explicitly.
Value
Invisibly returns NULL.
See Also
graphics::plot(),
stats::lm(),
stats::loess(),
bedrock::callIf()
Other plot.bivariate:
plotAssoc(),
plotBag(),
plotBubble(),
plotCor(),
plotDens2D(),
plotHeatmap(),
plotHexbin(),
plotMosaic()
Examples
plotXY(temperature ~ delivery_min, bedrock::Pizza,
main = "Temperature vs. Delivery Time")
# Suppress loess, customize lm line
plotXY(temperature ~ delivery_min, bedrock::Pizza,
lm = list(col = "darkred", lwd = 2),
loess = FALSE)
# No title, compact top margin
plotXY(temperature ~ delivery_min, bedrock::Pizza, main = "")
# subset, evaluated in data
plotXY(temperature ~ delivery_min, bedrock::Pizza,
subset = area == "Camden")
Draw a Polar Grid with Optional Labels
Description
Adds a polar coordinate grid (circles and radial lines) to an existing plot. Optionally includes labels for radii and angles.
Usage
polarGrid(
nRadial = NULL,
nAngular = NULL,
radialLabels = NULL,
angleLabels = NULL,
labelRadians = FALSE,
col = "lightgray",
lty = "dotted",
lwd = par("lwd"),
cex = 1,
las = 1,
adj = NULL,
dist = NULL
)
Arguments
nRadial |
numeric or vector controlling radial grid lines:
|
nAngular |
numeric or vector controlling angular grid lines:
|
radialLabels |
optional labels for radial grid lines (excluding zero).
If |
angleLabels |
optional labels for angular grid lines.
If |
labelRadians |
logical; if |
col |
color of grid lines. |
lty |
line type for grid lines. |
lwd |
line width for grid lines. |
cex |
character expansion factor for the labels. |
las |
integer controlling label orientation (as in |
adj |
numeric vector specifying text justification. |
dist |
numeric distance from origin for angular labels. |
Details
This function is intended to be used together with polar plotting functions
such as plotPolar. It assumes an existing plot with equal aspect ratio.
Radial grid lines are drawn as concentric circles, while angular grid lines are drawn as segments from the origin.
Label placement and formatting can be customized via adj, las,
and dist.
Value
Invisibly returns NULL.
See Also
Other graphics.setup:
canvas(),
setBackCol()
Examples
plot(0, 0, type = "n", xlim = c(-1, 1), ylim = c(-1, 1), asp = 1)
polarGrid()
# custom grid
plot(0, 0, type = "n", xlim = c(-2, 2), ylim = c(-2, 2), asp = 1)
polarGrid(nRadial = 4, nAngular = 8, col = "gray")
# suppress labels
polarGrid(radialLabels = NA, angleLabels = NA)
Draw Polygonal Geometries
Description
Generic function for drawing polygon-based geometry objects.
This function extends graphics::polygon() with support for
geometry objects such as circle(), ellipse(), regPolygon() and ring()
and further remains fully compatible with its original interface.
#'
For ordinary coordinate vectors the call is forwarded to
graphics::polygon(). Geometry objects such as
circle(), ellipse(), regPolygon()
and ring() are dispatched to specialised methods.
Usage
polygonX(x, ...)
## Default S3 method:
polygonX(
x,
y = NULL,
density = NULL,
angle = 45,
border = NULL,
col = NA,
lty = par("lty"),
...,
fillOddEven = FALSE
)
## S3 method for class 'ringGeometry'
polygonX(x, rule = "evenodd", ...)
## S3 method for class 'polygonGeometry'
polygonX(x, ...)
Arguments
x |
an object to be drawn. |
... |
further arguments passed to the corresponding method. |
y |
numeric vector of y-coordinates. |
density |
density of shading lines. |
angle |
angle of shading lines in degrees. |
border |
border colour. |
col |
fill colour. |
lty |
line type. |
fillOddEven |
logical; should the odd-even rule be used for filling? |
rule |
character string specifying the filling rule passed to
|
Value
Invisibly returns x.
See Also
Other geometry.structures:
arc(),
band(),
bezier(),
circle(),
ellipse(),
regPolygon(),
ring()
Examples
canvas()
polygonX(
circle(radius = 1),
col = "lightblue"
)
polygonX(
regPolygon(
radius = 0.7,
nVertices = 5
),
border = "red"
)
Preview an Object
Description
Generic function for an explicit, on-demand preview of an object, as
distinct from print(). preview() exists for object types
where print() is shared with another package's S3 generic
dispatch (e.g. class "html", used both by pharos and
htmltools for genuinely different purposes), so that registering
an own print.* method would silently overwrite - or be
overwritten by - the other package's behaviour.
Usage
preview(x, ...)
## Default S3 method:
preview(x, ...)
Arguments
x |
object to preview. |
... |
further arguments passed to methods. |
Details
The default method simply calls print(), so preview() is
always safe to call even for types with no dedicated method.
Value
x, invisibly. Called for its side effect of displaying the
object.
See Also
Other html:
asFileLink(),
asHtml(),
asImg(),
embedFile(),
escapeHtml(),
htmlNotation,
htmlSubscript,
preview.html(),
toHtmlTable()
Examples
# without a dedicated method the object is simply printed
preview(1:3)
# HTML markup is rendered as text
preview(asHtml("<b>Note:</b> R<sup>2</sup> = 0.87"))
Print HTML markup as readable text
Description
Renders an "html" object as text in the console: tags are
stripped or translated (<sub>/<sup> become
_/^, <b>/<strong>/<i>/<em>
become bold/italic via ANSI codes), common HTML entities
( , β, ...) are decoded, and <table>
blocks are rendered as aligned text tables.
Usage
## S3 method for class 'html'
preview(x, ...)
Arguments
x |
an object of class |
... |
further arguments, currently unused (kept for
consistency with |
Details
If output does not support ANSI styling, bold/italic markup is rendered as plain text (handled automatically by cli).
Value
x, invisibly
See Also
Other html:
asFileLink(),
asHtml(),
asImg(),
embedFile(),
escapeHtml(),
htmlNotation,
htmlSubscript,
preview(),
toHtmlTable()
Examples
preview(asHtml(
"<b>Model:</b> y = β<sub>0</sub> + β<sub>1</sub>x + ϵ"
))
# tables are rendered as aligned text
m <- matrix(c(12.3, 4.56, 7.8, 91.2), nrow = 2,
dimnames = list(c("a", "b"), c("mean", "sd")))
preview(toHtmlTable(m))
Print Object with Unit
Description
S3 method for printing objects with a "Unit" class.
Displays the value along with its associated unit.
Usage
## S3 method for class 'Unit'
print(x, ...)
Arguments
x |
an object with class |
... |
additional arguments passed to |
Value
Invisibly returns x.
See Also
Other format:
convUnit(),
fm(),
fmCI(),
style(),
unit()
Examples
x <- 10
unit(x) <- "m"
class(x) <- "Unit"
print(x)
Regular Polygon Geometry
Description
Create a regular polygon.
Usage
regPolygon(x = 0, y = 0, radius = 1, nVertices = 6, startAngle = 0)
Arguments
x, y |
centre coordinates. |
radius |
circumradius. |
nVertices |
number of vertices. |
startAngle |
staring angle in radians. |
Value
An object inheriting from class "regPolygonGeometry".
See Also
Other geometry.structures:
arc(),
band(),
bezier(),
circle(),
ellipse(),
polygonX(),
ring()
Examples
canvas(xlim = c(-2, 2))
# a hexagon is the default
polygonX(regPolygon(radius = 1.8), col = "lightblue")
# a square, once standing on a vertex and once on an edge
polygonX(regPolygon(radius = 1.2, nVertices = 4), border = "red")
polygonX(regPolygon(radius = 1.2, nVertices = 4, startAngle = pi/4))
# a triangle pointing upwards
polygonX(regPolygon(radius = 0.5, nVertices = 3, startAngle = pi/2),
col = "royalblue")
Convert RGB to CMY
Description
Convert RGB colors to the CMY color space.
Usage
rgbToCmy(col, maxColorValue = 1)
Arguments
col |
RGB matrix with one color per row (columns red, green and blue), or a vector of hexadecimal colors. |
maxColorValue |
maximum channel value of |
Value
Numeric CMY matrix with one color per row.
See Also
Examples
# one color per row, channels on a scale from 0 to 1
rgbToCmy(matrix(c(1, 0.39, 0.28), nrow = 1))
# the channels of hexadecimal colors run from 0 to 255
rgbToCmy(c("#FF6347", "#4169E1"), maxColorValue = 255)
Convert RGB Colors to the Nearest Named R Color
Description
Finds, for each color, the perceptually closest of the named R colors
(grDevices::colors()).
Usage
rgbToCol(col, method = c("ciede2000", "cie76"))
Arguments
col |
colors: an RGB matrix with one color per column and
channels on a scale from 0 to 255, as returned by |
method |
color difference formula, |
Details
The colors are converted from sRGB to the CIELAB color space with
grDevices::convertColor() (reference white D65), where distances
approximate perceived differences far better than in RGB or HSV. Two
color difference formulas are available:
"ciede2000"CIEDE2000, the current CIE recommendation. It corrects the shortcomings of CIE76 in the blue region and for saturated and near-neutral colors.
"cie76"CIE76, the Euclidean distance in CIELAB. Simpler, slightly less accurate.
Value
Character vector of named R colors, one per color in col;
NA for a missing color.
References
Sharma, G., Wu, W., & Dalal, E. N. (2005). The CIEDE2000 color-difference formula: Implementation notes, supplementary test data, and mathematical observations. Color Research & Application, 30(1), 21–30. doi:10.1002/col.20070
See Also
Examples
rgbToCol(matrix(c(162, 42, 42), nrow = 3))
rgbToCol(c("#A22A2A", "#4169E0"))
# CIE76 instead of CIEDE2000
rgbToCol(c("#A22A2A", "#4169E0"), method = "cie76")
Convert RGB to Hexadecimal Colors
Description
Convert RGB values to hexadecimal color strings.
Usage
rgbToHex(col)
Arguments
col |
RGB matrix with one color per column, as returned by
|
Value
Character vector of hexadecimal colors, one per color.
See Also
Examples
rgbToHex(c(162, 42, 42))
# one color per column, as returned by colToRgb()
rgbToHex(colToRgb(c("tomato", "royalblue")))
Convert RGB to Long Integers
Description
Encode RGB colors as long integers.
Usage
rgbToLong(col)
Arguments
col |
RGB matrix. |
Value
Integer vector.
See Also
Examples
rgbToLong(colToRgb(c("red", "green", "blue")))
Ring Geometry
Description
Create one or more rings or ring segments.
Usage
ring(
x = 0,
y = 0,
innerRadius = 0.5,
outerRadius = 1,
startAngle = 0,
endAngle = 2 * pi,
nPoints = 100
)
Arguments
x, y |
centre coordinates. |
innerRadius |
radius of the inner boundary. |
outerRadius |
radius of the outer boundary. |
startAngle, endAngle |
start and end angle in radians. |
nPoints |
number of points used for each boundary. |
Value
An object inheriting from class "ringGeometry" or a
"geometryCollection".
See Also
Other geometry.structures:
arc(),
band(),
bezier(),
circle(),
ellipse(),
polygonX(),
regPolygon()
Examples
canvas(xlim = c(-2, 2))
# a full ring
polygonX(ring(innerRadius = 1.4, outerRadius = 1.8), col = "lightblue")
# two ring segments at once
r <- ring(innerRadius = c(0.3, 0.8), outerRadius = c(0.7, 1.2),
startAngle = c(0, pi), endAngle = c(pi/2, 3*pi/2))
polygonX(r, col = c("tomato", "royalblue"))
Rotate a Geometric Structure
Description
Rotate a geometric structure by an angle theta around a centerpoint xy.
Usage
rotate(x, y = NULL, mx = NULL, my = NULL, theta = pi/3, asp = 1)
Arguments
x, y |
vectors containing the coordinates of the vertices of the polygon
, which has to be rotated. The coordinates can be passed in a plotting
structure (a list with x and y components), a two-column matrix, .... See
|
mx, my |
xy-coordinates of the center of the rotation. If left to NULL, the centroid of the structure will be used. |
theta |
angle of the rotation |
asp |
the aspect ratio for the rotation. Helpful for rotate structures along an ellipse. |
Value
The function invisibly returns a list of the coordinates for the rotated shape(s).
See Also
polygonX(), regPolygon(),
ellipse(), arc()
Other geometry.transformation:
transformXY()
Examples
op <- par(no.readonly = TRUE)
# let's have a triangle
canvas(main="Rotation")
x <- regPolygon(nVertices=3)
# and rotate
sapply( (0:3) * pi/6, function(theta) {
xy <- rotate( x=x, theta=theta )
polygon(xy, col=addOpacity("blue", 0.2))
} )
abline(v=0, h=0)
par(op)
Background of a Plot
Description
Paints the background of the plot, using either the figure region, the plot region or both. It can sometimes be cumbersome to elaborate the coordinates and base R does not provide a simple function for that.
Usage
setBackCol(col = "grey", region = c("plot", "figure"), border = NA)
Arguments
col |
the color of the background, if two colors are provided, the first is used for the plot region and the second for the figure region. |
region |
either |
border |
color for rectangle border(s). Default is |
Value
No return value (invisible NULL), called for its side effect of
painting the background of the current plot.
See Also
Other graphics.setup:
canvas(),
polarGrid()
Examples
# use two different colors for the figure region and the plot region
plot(x = rnorm(100), col="blue", cex=1.2, pch=16,
panel.first={setBackCol(c("red", "lightyellow"))
grid()})
Produce a shaded Curve
Description
Sometimes the area under a density curve has to be color shaded, for
instance to illustrate a p-value or a specific region under the normal
curve. This function draws a curve corresponding to a function over the
interval [from, to]. It can plot also an expression in the variable
xname, default x.
Usage
shade(expr, col = par("fg"), breaks, density = 10, n = 101, xname = "x", ...)
Arguments
expr |
the name of a function, or a |
col |
color to fill or shade the shape with. The default is taken from
|
breaks |
numeric, a vector giving the breakpoints between the distinct areas to be shaded differently. Should be finite as there are no plots with infinite limits. |
density |
the density of the lines as needed in polygon. |
n |
integer; the number of x values at which to evaluate. Default is 101. |
xname |
character string giving the name to be used for the x axis. |
... |
the dots are passed on to |
Details
Useful for shading the area under a curve as often needed for explaining significance tests.
Value
A list with components x and y of the points that were
drawn is returned invisibly.
See Also
Other plot.distribution:
plotFun(),
plotProbDist()
Examples
curve(dt(x, df=5), xlim=c(-6,6),
main=paste("Student t-Distribution Probability Density Function, df = ", 5, ")", sep=""),
type="n", las=1, ylab="probability", xlab="t")
shade(dt(x, df=5), breaks=c(-6, qt(0.025, df=5), qt(0.975, df=5), 6),
col=c("deeppink4", "skyblue3"), density=c(20, 7))
Add a Spline Smoother
Description
Fit a smoothing spline and optionally add confidence bands.
Usage
splineX(x, ...)
## Default S3 method:
splineX(x, ...)
## S3 method for class 'formula'
splineX(formula, data, subset, na.action = na.omit, weights, ...)
## S3 method for class 'SplineX'
lines(
x,
col = pal()[1],
lwd = 2,
lty = "solid",
type = "l",
band = list(conf.level = 0.95),
...
)
Arguments
x |
spline object returned by |
... |
for |
formula |
A formula of the form |
data |
an optional matrix or data frame (or similar; see
|
subset |
an optional vector specifying a subset of observations to be used in the analysis. |
na.action |
A function which indicates what should happen when
the data contain |
weights |
optional vector of weights, a column of |
col |
line color of the smoother. |
lwd |
line width. |
lty |
line type. |
type |
plotting type passed to |
band |
controls the confidence band. May be |
Details
Confidence bands are controlled via band. These arguments can be:
-
FALSE,NULLorNA: suppress the band -
TRUE: draw the band with default settings a named list: customize the band appearance and confidence level
Value
splineX() returns the fit of stats::smooth.spline() with the
additional class "SplineX". The lines() method returns no value
(invisible NULL); it is called for its side effect of adding the smoother
and its confidence band to the current plot.
See Also
Other graphics.trendlines:
lines.lm(),
lines.loess()
Examples
op <- par(no.readonly = TRUE)
par(mfrow = c(1, 2))
x <- runif(100)
y <- rnorm(100)
plot(x, y)
lines(splineX(y ~ x))
plot(dist ~ speed, cars)
lines(splineX(dist ~ speed, cars))
# subset and weights, both evaluated in data
plot(dist ~ speed, cars)
lines(splineX(dist ~ speed, cars, subset = speed > 10,
weights = sqrt(speed)))
plot(dist ~ speed, cars)
lines(
splineX(dist ~ speed, cars),
band = list(
conf.level = 0.99,
col = addOpacity("red", 0.3),
border = "black"
)
)
par(op)
Spread Out a Vector of Numbers To a Minimum Interval
Description
Spread the numbers of a vector so that there is a minimum interval between any two numbers (in ascending or descending order). This is helpful when we want to place textboxes on a plot and ensure, that they do not mutually overlap.
Usage
spreadOut(x, minDist = NULL, cex = 1)
Arguments
x |
a numeric vector which may contain |
minDist |
the minimum interval between any two values. If this is left
to |
cex |
numeric character expansion factor; multiplied by
|
Details
spreadOut() starts at or near the middle of the vector and increases
the intervals between the ordered values. NAs are preserved.
spreadOut() first tries to spread groups of values with intervals
less than minDist out neatly away from the mean of the group. If this
doesn't entirely succeed, a second pass that forces values away from the
middle is performed.
spreadOut() can also be used to avoid overplotting of axis tick
labels where they may be close together.
Value
On success, the spread out values. If there are less than two valid values, the original vector is returned.
Note
This function is based on plotrix::spreadOut() and has been
integrated here with some minor changes.
Based on code by Jim Lemon jim@bitwrit.com.au
See Also
Other graphics.layout:
abcCoords(),
axTicksPosixct(),
axisBreak(),
isValidPlotRegion(),
lineToUser(),
mar(),
plotFacet()
Examples
spreadOut(c(1, 3, 3, 3, 3, 5), 0.2)
spreadOut(c(1, 2.5, 2.5, 3.5, 3.5, 5), 0.2)
spreadOut(c(5, 2.5, 2.5, NA, 3.5, 1, 3.5, NA), 0.2)
# this will almost always invoke the brute force second pass
spreadOut(rnorm(10), 0.5)
Date/Time/Directory Stamp the Current Plot
Description
Stamp the current plot in the extreme lower right corner. A free text or expression can be defined as text to the stamp.
Usage
stamp(text = .useTheme, las = NULL, cex = 0.6, col = "grey40")
Arguments
text |
character string, expression, or toggle controlling the
stamp text. |
las |
orientation; see |
cex, col |
size and color of the stamp text. |
Details
The default text is taken from the active theme (see theme). If user and date should be included by default, an unevaluated expression, which is evaluated when the stamp is drawn, will help:
setTheme(list(stamp = expression(gettextf("%s / %s",
Sys.getenv("USERNAME"), fm(Sys.Date(), fmt = "yyyy-MM-dd")))))
For R results may not be satisfactory if par(mfrow=) is in effect.
Value
The text of the stamp as a character string, invisibly; an empty string if the stamp is suppressed.
See Also
Other graphics.annotation:
barText(),
boxedText(),
colLegend(),
errBars(),
textLegend(),
titleRect()
Examples
plot(1:20)
stamp()
Abbreviate Strings Uniquely
Description
Creates abbreviations of character strings such that they remain distinguishable within the input vector.
Usage
strAbbr(x, minChar = 1, method = c("left", "fix"))
Arguments
x |
a character vector |
minChar |
integer; minimum number of characters to retain |
method |
character string specifying the abbreviation strategy:
|
Details
The function ensures that abbreviations are unique (within the given
vector) while respecting the minimum length minChar.
For method = "left", each string is shortened individually to the
shortest prefix that distinguishes it from all others.
For method = "fix", a single prefix length is chosen such that all
strings are distinguishable.
Unicode-aware substring operations are performed using the stringi package.
Value
A character vector of abbreviated strings.
See Also
stringi::stri_sub(),
stringi::stri_length()
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("apple", "apricot", "banana")
# individual minimal abbreviations
strAbbr(x, method = "left")
# fixed length abbreviations
strAbbr(x, method = "fix")
Align Strings
Description
Aligns a character vector to the left, right, center, or with respect to the first occurrence of a specified separator.
Usage
strAlign(x, sep = "\\r")
Arguments
x |
a character vector |
sep |
a character specifying the alignment mode:
|
Details
Alignment is achieved by padding strings with spaces so that all elements have equal width. This is mainly useful for monospaced output.
For left, right, and center alignment, strings are padded to the maximum width using spaces.
If a separator is provided, strings are aligned such that the first occurrence of the separator is vertically aligned. If a string does not contain the separator, it is treated as if the separator occurred at the end.
This function uses Unicode-aware string handling via the stringi package.
Value
A character vector of aligned strings.
See Also
stringi::stri_pad(),
stringi::stri_sub(),
stringi::stri_trim_right()
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("here", "there", "everywhere")
# right align (default)
strAlign(x)
# left align
strAlign(x, "\\l")
# center align
strAlign(x, "\\c")
# align at decimal separator
z <- c("6.0", "45.12", "784")
strAlign(z, ".")
Capitalize Strings
Description
Capitalizes character strings in different ways: first letter, each word, or title case.
Usage
strCap(x, method = c("first", "word", "title"))
Arguments
x |
a character vector |
method |
character string specifying the capitalization method:
|
Details
The function uses Unicode-aware transformations from the stringi package.
For method = "title", common stopwords (e.g., "a",
"the", "of") remain lowercase unless they appear
as part of another word.
Value
A character vector with capitalized strings.
See Also
stringi::stri_trans_totitle(),
stringi::stri_split_boundaries()
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("hello world", "the lord of the rings")
# first letter
strCap(x, "first")
# each word
strCap(x, "word")
# title case
strCap(x, "title")
Split a String into a Number of Sections of Defined Length
Description
Splitting a string into a number of sections of defined length is needed, when we want to split a table given as a number of lines without separator into columns. The cutting points can either be defined by the lengths of the sections or directly by position.
Usage
strChop(x, len = NULL, pos = NULL)
Arguments
x |
the string to be cut in pieces |
len |
a vector with the lengths of the pieces |
pos |
a vector of cutting positions. Will be ignored when |
Details
If length is going over the end of the string the last part will be returned, so if the rest of the string is needed, it's possible to simply enter a big number as last partlength.
len and pos can't be defined simultaneously, only
alternatively.
Typical usages are
strChop(x, len) strChop(x, pos)
Value
a vector with the parts of the string.
See Also
string-overview for an overview of all string utilities in pharos.
Examples
x <- paste(letters, collapse="")
strChop(x=x, len = c(3,5,2))
# and with the rest integrated
strChop(x=x, len = c(3, 5, 2, nchar(x)))
# cutpoints at 5th and 10th position
strChop(x=x, pos=c(5, 10))
Count Words in Strings
Description
Counts the number of words in each element of a character vector.
Usage
strCountWords(x)
Arguments
x |
a character vector |
Details
Words are detected using Unicode-aware word boundaries as implemented in stringi. This ensures robust handling of different languages, punctuation, and whitespace.
Value
An integer vector giving the number of words in each element of
x.
See Also
string-overview for an overview of all string utilities in pharos.
Examples
strCountWords("This is a sentence.")
strCountWords(c("One word", "Two words here", NA))
Compute Distances Between Strings
Description
strDist computes distances between strings following to Levenshtein
or Hamming method.
Usage
strDist(
x,
y,
method = c("levenshtein", "normlevenshtein", "hamming"),
mismatch = 1,
gap = 1,
ignoreCase = FALSE
)
Arguments
x |
character vector, first string |
y |
character vector, second string |
method |
character, name of the distance method. This must be
|
mismatch |
numeric, distance value for a mismatch between symbols |
gap |
numeric, distance value for inserting a gap |
ignoreCase |
if |
Details
The function computes the Hamming and the Levenshtein (edit) distance of two given strings (sequences). The Hamming distance between two vectors is the number of mismatches between corresponding entries.
In case of the Hamming distance the two strings must have the same length.
In case of the Levenshtein (edit) distance a scoring and a trace-back matrix
are computed and are saved as attributes "ScoringMatrix" and
"TraceBackMatrix". The numbers in the trace-back matrix reflect
insertion of a gap in string y (1), match/mismatch (2), and
insertion of a gap in string x (3).
The edit distance is useful, but normalizing the distance to fall within the
interval [0,1] is preferred because it is somewhat difficult to judge whether
an LD of for example 4 suggests a high or low degree of similarity. The
method "normlevenshtein" for normalizing the LD is sensitive to this
scenario. In this implementation, the Levenshtein distance is transformed to
fall in this interval as follows:
lnd = 1 - \frac{ld}{max(length(x),
length(y))}
where ld is the edit distance and max(length(x), length(y))
denotes that we divide by the length of the larger of the two character
strings. This normalization, referred to as the Levenshtein normalized
distance (lnd), yields a statistic where 1 indicates perfect agreement
between the two strings, and a 0 denotes imperfect agreement. The closer a
value is to 1, the more certain we can be that the character strings are the
same; the closer to 0, the less certain.
Value
strDist returns an object of class "dist"; cf.
stats::dist().
Note
For distances between strings and for string alignments see also Bioconductor package Biostrings
Based on code by Matthias Kohl, adapted to conform to package standards.
References
R. Merkl and S. Waack (2009) Bioinformatik Interaktiv. Wiley.
Harold C. Doran (2010) MiscPsycho. An R Package for Miscellaneous Psychometric Analyses
See Also
string-overview for an overview of all string utilities in pharos.
Examples
x <- "GACGGATTATG"
y <- "GATCGGAATAG"
## Levenshtein distance
d <- strDist(x, y)
d
attr(d, "ScoringMatrix")
attr(d, "TraceBackMatrix")
## Hamming distance
strDist(x, y, method="hamming")
Extract First Match from Strings
Description
Extracts the first substring matching a regular expression from each element of a character vector.
Usage
strExtract(x, pattern, ...)
Arguments
x |
a character vector |
pattern |
a character string containing a regular expression to match |
... |
additional arguments passed to
|
Details
This function is a thin wrapper around
stringi::stri_extract_first_regex() providing a simplified
interface for extracting the first match of a pattern.
Value
A character vector containing the first match for each element of
x. If no match is found, NA is returned.
See Also
stringi::stri_extract_first_regex(),
strExtractBetween()
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("abc123", "no digits", "456xyz")
# extract first number
strExtract(x, "\\d+")
# extract words
strExtract("hello world", "\\w+")
Extract Substrings Between Patterns
Description
Extracts substrings that occur between two delimiters.
Usage
strExtractBetween(x, left, right, greedy = FALSE)
Arguments
x |
a character vector |
left |
a character string or regular expression marking the left boundary |
right |
a character string or regular expression marking the right boundary |
greedy |
logical; if |
Details
The function uses regular expressions to extract the first substring
between left and right. Internally, it constructs a pattern
of the form:
greedy:
left (.*) rightnon-greedy:
left (.*?) right
Extraction is performed using stringi::stri_match_first_regex(),
which returns the first captured group.
Value
A character vector containing the extracted substrings. If no match
is found, NA is returned for that element.
See Also
stringi::stri_match_first_regex(),
strExtract()
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("a[123]b", "x[abc]y", "no match")
# non-greedy (default)
strExtractBetween(x, "\\[", "\\]")
# greedy
strExtractBetween("a[1]b[2]c", "\\[", "\\]", greedy = TRUE)
Check if Character Strings Represent Numeric Values
Description
Determines whether elements of a character vector represent valid numeric values.
Unlike as.numeric(), this function performs a regex-based validation and
does not produce warnings.
Usage
strIsNumeric(x, scientific = FALSE)
Arguments
x |
a character vector to be tested |
scientific |
logical; if |
Details
The function uses regular expressions via stringi to validate numeric formats.
Valid formats include optional leading sign (+ or -), optional decimal
point, and digits. If scientific = TRUE, exponential notation using e
or E is also supported.
Note that special values such as "Inf", "-Inf", and "NaN" are
not considered numeric by this function.
Value
A logical vector of the same length as x, indicating whether each
element represents a numeric value.
See Also
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("123", "-3.141", "1e3", "foo", "Inf")
strIsNumeric(x)
strIsNumeric(x, scientific = TRUE)
Returns the Left Or the Right Part Of a String
Description
Returns the left part or the right part of a string. The number of
characters are defined by the argument n. If n is negative,
this number of characters will be cut off from the other side.
Usage
strLeft(x, n)
strRight(x, n)
Arguments
x |
a vector of strings |
n |
a positive or a negative integer, the number of characters to cut.
If n is negative, this number of characters will be cut off from the right
with |
Details
The functions strLeft and strRight are simple wrappers to
substr.
Value
the left (right) n characters of x
See Also
string-overview for an overview of all string utilities in pharos.
Examples
strLeft("Hello world!", n=5)
strLeft("Hello world!", n=-5)
strRight("Hello world!", n=6)
strRight("Hello world!", n=-6)
strLeft(c("Lorem", "ipsum", "dolor","sit","amet"), n=2)
strRight(c("Lorem", "ipsum", "dolor","sit","amet"), n=c(2,3))
String length
Description
Intuitive alias for nchar().
Usage
strLen(x, ...)
Arguments
x |
a character vector |
... |
further arguments passed to |
Value
An integer vector with the number of characters of the elements of
x, see nchar().
See Also
string-overview for an overview of all string utilities in pharos.
Examples
strLen(c("pharos", "", NA))
strLen(month.name)
# a number is converted to a string first
strLen(123456)
Pad a String With Justification
Description
strPad will fill a string x with defined characters to fit a given
length.
Usage
strPad(x, width = NULL, pad = " ", align = c("left", "right", "center"))
Arguments
x |
a vector of strings to be padded |
width |
resulting width of padded string. If x is a vector and width is left to NULL, it will be set to the length of the largest string in x. |
pad |
string to pad with. Will be repeated as often as necessary. Default is " ". |
align |
adjustment of the old string, one of |
Details
If a string x has more characters than width, it will be chopped on the length of width.
Value
the string
See Also
string-overview for an overview of all string utilities in pharos.
Examples
strPad("My string", 25, "XoX", "center")
# [1] "XoXXoXXoMy stringXXoXXoXX"
Find Position of First Occurrence Of a String
Description
Returns the numeric position of the first occurrence of a substring within a
string. If the search string is not found, the result will be NA.
Usage
strPos(x, pattern, pos = 1)
Arguments
x |
a character vector in which to search for the pattern, or an object which can be coerced by as.character to a character vector |
pattern |
character string (search string) containing the pattern to be matched in the given character vector. This can be a character string or a regular expression. |
pos |
integer, defining the start position for the search within x. The result will then be relative to the begin of the truncated string. Will be recycled. |
Details
This is just a wrapper for the function regexpr().
Value
a vector of the first position of pattern in x
See Also
string-overview for an overview of all string utilities in pharos.
Examples
strPos(x=rownames(mtcars), pattern="y")
# first t, starting with position 4
strPos(x=rownames(mtcars), pattern="t", pos=4)
Reverse Strings
Description
Reverses each element of a character vector.
Usage
strRev(x)
Arguments
x |
a character vector |
Details
This function uses stringi::stri_reverse(), which correctly
handles Unicode characters and multi-byte encodings.
Value
A character vector with each string reversed.
See Also
string-overview for an overview of all string utilities in pharos.
Examples
strRev("abc")
strRev(c("hello", "world"))
# Unicode-safe
strRev("äöü")
Spell Strings Using Phonetic Alphabets
Description
Converts characters in a string into their corresponding phonetic representations using either the NATO phonetic alphabet or Morse code.
Usage
strSpell(x, upr = "CAP", type = c("nato", "morse"))
Arguments
x |
a character vector (typically of length 1) |
upr |
character string used as a prefix for uppercase letters.
Default is |
type |
character string specifying the encoding system:
|
Details
Letters (A–Z, a–z) and digits (0–9) are mapped to their corresponding phonetic representations. Other characters are returned unchanged.
For type = "nato", uppercase letters can optionally be prefixed
(e.g., "CAP Alfa") to distinguish them from lowercase letters.
The function uses Unicode-aware character splitting via
stringi::stri_split_boundaries().
Value
A character vector with each character of x replaced by its
phonetic representation.
See Also
strTrim(),
stringi::stri_split_boundaries()
string-overview for an overview of all string utilities in pharos.
Examples
# NATO spelling
strSpell("ABC")
# with digits
strSpell("A1B2")
# Morse code
strSpell("SOS", type = "morse")
# without uppercase prefix
strSpell("ABC", upr = NA)
Split Strings
Description
Splits character vectors into substrings. This is a convenience wrapper
around stringi::stri_split_fixed() and
stringi::stri_split_regex() with simplified defaults.
Usage
strSplit(x, split = "", fixed = FALSE)
Arguments
x |
a character vector to be split |
split |
a character string specifying the delimiter (if
|
fixed |
logical; if |
Details
If the input x has length 1, the result is returned as a character
vector instead of a list for convenience.
This function provides a simplified interface to string splitting using
the stringi package. It avoids some of the complexity of
base::strsplit() while providing consistent and Unicode-aware
behavior.
Value
A list of character vectors. If x has length 1, a character
vector is returned.
See Also
stringi::stri_split_fixed(),
stringi::stri_split_regex(), base::strsplit()
string-overview for an overview of all string utilities in pharos.
Examples
strSplit("a,b,c", ",", fixed = TRUE)
strSplit(c("a b", "c d"), " ")
# regex splitting
strSplit("a1b2c3", "\\d")
Remove Leading/Trailing Whitespace From A String
Description
The function removes whitespace characters as spaces, tabs and newlines from
the beginning and end of the supplied string. Whitespace characters
occurring in the middle of the string are retained.
Trimming with method
"left" deletes only leading whitespaces, "right" only
trailing. Designed for users who were socialized by SQL.
Usage
strTrim(x, pattern = " \t\n", method = c("both", "left", "right"))
Arguments
x |
the string to be trimmed |
pattern |
the pattern of the whitespaces to be deleted, defaults to
space, tab and newline: |
method |
one out of |
Details
The functions are defined depending on method as
both: gsub( pattern=gettextf("^[\%s]+|[\%s]+$", pattern, pattern), replacement="", x=x)
left: gsub( pattern=gettextf("^[\%s]+",pattern), replacement="", x=x)
right: gsub( pattern=gettextf("[\%s]+$",pattern), replacement="", x=x)
Value
the string x without whitespaces
See Also
string-overview for an overview of all string utilities in pharos.
Examples
strTrim(" Hello world! ")
strTrim(" Hello world! ", method="left")
strTrim(" Hello world! ", method="right")
# user defined pattern
strTrim(" ..Hello ... world! ", pattern=" \\.")
Truncate Strings and Add Ellipses If a String is Truncated.
Description
Truncates one or more strings to a specified length, adding an ellipsis
(...) to those strings that have been truncated. The truncation can also be
performed using word boundaries. Use strAlign() to justify
the strings if needed.
Usage
strTrunc(x, maxLen = 20, ellipsis = "...", wordBound = FALSE)
Arguments
x |
a vector of strings |
maxLen |
the maximum length of the returned strings (NOT counting the
appended ellipsis). |
ellipsis |
the string to be appended, if the string is longer than the
given maximal length. The default is |
wordBound |
logical. Determines if the maximal length should be reduced to
the next smaller word boundary and so words are not chopped. Default is
|
Value
The string(s) passed as ‘x’ now with a maximum length of ‘maxLen’ + 3 (for the ellipsis).
See Also
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("this is short", "and this is a longer text",
"whereas this is a much longer story, which could not be told shorter")
# simple truncation on 10 characters
strTrunc(x, maxLen=10)
# NAs remain NA
strTrunc(c(x, NA_character_), maxLen=15, wordBound=TRUE)
# using word boundaries
for(i in 0:20)
print(strTrunc(x, maxLen=i, wordBound=TRUE))
# compare
for(i in 0:20)
print(strTrunc(x, maxLen=i, wordBound=FALSE))
Extract Numeric Values from Strings
Description
Extracts numeric values from character strings using regular expressions. The function supports integers, decimal numbers, and scientific notation.
Usage
strVal(
x,
collapse = FALSE,
output = c("character", "numeric"),
dec = getOption("OutDec")
)
Arguments
x |
a character vector |
collapse |
logical; if |
output |
character; controls the type of the returned values.
|
dec |
character; decimal separator used in the input. Defaults to
|
Details
The function detects numeric values including optional signs, decimal parts,
and scientific notation (e.g., "1.23e-4").
Whitespace between sign and number (e.g., "- 2.5") is tolerated and
removed before returning results.
If output = "numeric" and the decimal separator dec differs
from the current system setting (getOption("OutDec")), values are
converted accordingly before coercion.
Value
If collapse = FALSE, a list of character or numeric vectors
containing the extracted values for each element of x.
If collapse = TRUE, a character or numeric vector with
concatenated values per element.
See Also
as.numeric(), stringi::stri_extract_all_regex()
string-overview for an overview of all string utilities in pharos.
Examples
x <- c("value = 12.5", "x = -3.2e2 and 7", "no numbers here")
# extract as character
strVal(x)
# extract as numeric
strVal(x, output = "numeric")
# concatenate values
strVal(x, collapse = TRUE)
# different decimal separator
strVal("value = 3,14", dec = ",", output = "numeric")
String Functions in pharos
Description
pharos provides a family of functions for manipulating and inspecting character strings, built on top of stringi for Unicode-aware behavior. They fall into two groups:
Manipulation – transform, extract, or reshape string content:
| Function | Purpose |
strAbbr() | Abbreviate strings uniquely |
strAlign() | Align strings |
strCap() | Capitalize strings |
strChop() | Split a string into a number of sections of defined length |
strExtract() | Extract first match from strings |
strExtractBetween() | Extract substrings between patterns |
strLeft() / strRight() | Return the left or the right part of a string |
strPad() | Pad a string with justification |
strRev() | Reverse strings |
strSpell() | Spell strings using phonetic alphabets |
strSplit() | Split strings |
strTrim() | Remove leading/trailing whitespace from a string |
strTrunc() | Truncate strings and add ellipses if a string is truncated |
strVal() | Extract numeric values from strings |
Information – inspect properties of strings without changing them:
| Function | Purpose |
strCountWords() | Count words in strings |
strDist() | Compute distances between strings |
strIsNumeric() | Check if character strings represent numeric values |
strLen() | String length |
strPos() | Find position of first occurrence of a string |
See Also
Format Styles
Description
Interface for format templates, defined as a list consisting of any accepted
format features in fm(). This enables to define templates globally
and easily change or modify them later.
Usage
styles()
style(
x,
digits = NULL,
leadDigits = NULL,
sci = NULL,
bigMark = NULL,
decMark = NULL,
naForm = NULL,
zeroForm = NULL,
fmt = NULL,
pThreshold = NULL,
width = NULL,
align = NULL,
lang = NULL,
label = NULL,
...
)
## S3 method for class 'Style'
print(x, ...)
Arguments
x |
an object of class |
digits |
integer, the desired (fixed) number of digits after the
decimal point. You will always get this number of digits, even if the last
digit is 0. In scientific notation it is the number of decimals of the
mantissa. Negative numbers of digits round to
a power of ten ( |
leadDigits |
number of leading zeros. |
sci |
numeric scalar giving the absolute power-of-ten threshold for
scientific notation. It applies to the absolute value of |
bigMark |
character; if not empty used as mark between every 3
digits before the decimal point. If |
decMark |
character specifying the decimal mark. If |
naForm |
character, string specifying how |
zeroForm |
character, string specifying how zeros should be specially
formatted. Useful for pretty printing 'sparse' objects. If set to
|
fmt |
a format code or date-time template, or a formatting function.
See the Details of |
pThreshold |
positive numeric threshold below which p-values are shown
as |
width |
nonnegative integer giving the minimum display width |
align |
the character on whose position the strings will be aligned.
Left alignment can be requested by setting |
lang |
optional value setting the language for the months and daynames.
Can be either |
label |
a description for the style |
... |
for |
Details
style() takes any of the arguments of fm() and combines them to an
object of class "Style", which then can be handed over to fm() as
argument fmt.
Following will define a new format template named
"num.sty". Passed to fm() this will result in a number
displayed with 2 fixed digits and a comma as big mark:
num.sty <- style(digits=2, bigMark=",") fm(12222.89345, fmt=num.sty) = 12,222.89
This is the same result as if the arguments would have been supplied
directly, but helps to avoid boilerplate code:
fm(12222.89345, digits=2, bigMark=",").
To derive a style from an existing one we can provide style() with the
style, or with its name, and overwrite, resp. add new format options.
style("num.sty", digits=1, sci=10) will use the current version of the
numeric format and change the digits to 1 and the threshold to switch to
scientific presentation to numbers >= 1e10 and < 1e-10. The stored style
itself is not changed, so the result has to be assigned.
styles() returns all found style definitions in the global
environment or in the options.
The styles can be stored as options for convenience. To store a new format
we use the default options() approach: options(num.sty = style(digits=1, bigMark=" ")) Defined styles in the options can be passed
on to fm() simply by their name. If a style of the same name exists in
the global environment, that one is used.
Four default styles are registered as options when pharos is loaded,
unless options of these names already exist: "abs.sty" for counts,
"num.sty" for numeric values, "per.sty" for percentages and
"pval.sty" for p-values. They are used by several plot functions of this
package (e.g. plotHeatmap()) and by the report functions in
DescToolsX (e.g. DescToolsX::tOne()). Redefining them with
options() changes these formats globally.
Value
style() returns an object of class Style
styles() returns a list of styles
See Also
Other format:
convUnit(),
fm(),
fmCI(),
print.Unit(),
unit()
Examples
# use style() to get and define new formats stored as option
num.sty <- style(digits=2, bigMark=" ")
abs.sty <- style(digits=0, bigMark=" ")
dat.sty <- style(fmt="MM, dd yyyy")
num.sty # displays the details of the style
# editing styles
style("abs.sty") # looks for format "abs.sty"
# style("nexist") # return for nonexisting style
style("abs.sty", bigMark="") # get Style("abs") and overwrite bigMark
style("abs.sty", naForm="-") # get Style("abs") and add user defined naForm
styles() # all defined formats
styles()[c("num.sty", "abs.sty")] # numeric and integer styles
# define totally new format and store as option
options(nob.sty=style(digits=5, naForm="nodat"))
# using styles
fm(314.1563, fmt=abs.sty)
fm(314.1563, fmt=num.sty)
fm(Sys.Date(), fmt=dat.sty)
# remove the option again
options(nob.sty=NULL)
Direct Labels in the Right Margin
Description
Draw a legend in the right margin consisting of short line segments
and text labels, placed next to the (typically last) values of the
plotted series. This labels lines directly instead of using a boxed
legend(), as commonly preferred for time series and
profile plots.
Usage
textLegend(
y,
labels = names(y),
line = c(1, 1),
width = 1,
col = par("fg"),
lty = par("lty"),
lwd = par("lwd"),
cex = par("cex"),
main = NULL,
minDist = NULL
)
Arguments
y |
numeric vector with the vertical anchor positions in user coordinates, typically the last observed value of each series, in series (column) order. Sorting and collision handling are done internally. |
labels |
character vector of labels, parallel to |
line |
numeric vector of length 1 or 2 (recycled), in margin lines of side 4. The first element is the offset of the segments from the plot region, the second the gap between segments and labels. |
width |
length of the line segments in margin lines. Set to
|
col, lty, lwd |
color, line type and width of the segments,
parallel to |
cex |
character expansion for the labels. Also enters the default vertical spacing, so larger text automatically gets wider spacing. |
main |
optional title for the legend, drawn at the top of the
plot region. Default is |
minDist |
minimal vertical distance between labels in user
coordinates, passed to |
Details
The function owns the legend geometry: the anchor positions y
are sorted internally so the legend follows the vertical order of the
lines, the graphical parameters are recycled accordingly, and vertical
label collisions are resolved via spreadOut(). Callers therefore
simply pass the values in series order, parallel to col,
lty and lwd.
Drawing uses mtext() and segments() in the
device margin; xpd is set to TRUE and restored on exit.
Horizontal positions are given in margin lines of side 4 and converted
to user coordinates via lineToUser().
Make sure the right margin is wide enough for segments and
labels, e.g. via the mar argument of the calling plot
function.
Value
The (sorted and spread) vertical label positions, invisibly. Useful for adding further annotation next to the labels.
See Also
plotLines(), mtext(),
segments(), legend()
Other graphics.annotation:
barText(),
boxedText(),
colLegend(),
errBars(),
stamp(),
titleRect()
Examples
m <- EuStockMarkets[seq(1, 1860, 10), ]
op <- par(mar = c(5, 4, 4, 8))
matplot(m, type = "l", lty = 1, lwd = 2, col = 1:4, las = 1,
main = "EU Stock Markets")
textLegend(y = m[nrow(m), ], labels = colnames(m),
col = 1:4, lwd = 2, main = "Index")
par(op)
pharos's Graphics and Formatting Theme
Description
getTheme(), setTheme(), and resetTheme() are the
user-facing entry points to pharos's theme system: a single, named list
of graphical and formatting defaults, consulted by essentially every
plotting function in the package (and by fm() for
numeric/percentage/p-value formatting) whenever the corresponding
function argument is left at its default value.
Usage
getTheme()
setTheme(theme)
resetTheme()
Arguments
theme |
either a named list of theme components to merge into the
active theme (only the given top-level elements are replaced; e.g.
|
Value
getTheme() and resetTheme() return the (new)
active theme, a named list; setTheme() returns the new active
theme as well, invisibly.
What the theme is for
Most graphical parameters in pharos's plotting functions (col,
grid, box, pch, ...) default to a sentinel value,
.useTheme, rather than to a hardcoded color or number. At call
time, that sentinel is resolved against getTheme() - so changing
the active theme changes the look of every plot produced
afterwards that didn't explicitly override that argument, without
touching a single plotting function's code.
This gives three independent ways to control a plot's appearance, in order of precedence (highest first):
-
Explicit argument, e.g.
plotXY(x, y, col = "red")- always wins, for that one call only. -
Function-specific default - some functions deliberately hardcode a value that differs from the generic theme baseline instead of using
.useTheme(e.g.plotBar()'sboxdefaults toFALSErather than the theme's box setting, andplotDot()'s grid line color/style stays its own orange/grey dashed look regardless of the active theme). This is a conscious per-function design choice, not a bug - see the individual function's documentation for which arguments opt out of theme-following this way. -
Active theme (
getTheme()) - the package-wide fallback used whenever neither of the above applies.
Structure of the theme
The theme is a named list with the following top-level components.
Nested components (grid, box, points, bar,
sty) are themselves named lists; setTheme() replaces them
wholesale (it does not merge one level deeper), so to change a single
nested value, supply the complete sub-list, e.g.
setTheme(list(grid = list(col = "red", lwd = 1, lty = "dotted"))).
parcol.axis="grey40", las=1, cex=1.1. Globalpar()pass applied by every.applyParFromDots()call (axis label color, axis label orientation, global text scaling).gridcol="grey80", lwd=1, lty="dotted", plusgroup.*variants. Background grid lines, via.drawGrid(). Thegroup.*entries style a subordinate/secondary grid (e.g. group separators) where a function draws one.boxcol="grey50", lwd=1, lty="solid". The frame drawn around a plot region, via.drawBox().pointspch=21, col="grey50", bg=addOpacity("grey"), cex=1.1. Default point styling for scatterplot-like functions (e.g.plotXY(),plotDot()).twinpal("helsana")[c(6, 1)]. A fixed pair of colors for contexts that inherently need exactly two contrasting colors (e.g. a fit line and a smoother inplotXY(), the two poles of a diverging color ramp inplotCor(), a single accent color viatwin[1]inlines.loess()/plotQQ()'s confidence band). Never used as a substitute forpalettewhen more than two colors are needed.palette"helsana". Name of the qualitative (categorical) palette used whenever more than two unordered colors are needed (e.g.plotMosaic()'s fill colors), resolved viapal(). Deliberately not used for sequential or diverging numeric scales – see the next item.- (none – by design)
Sequential/diverging numeric color scales (e.g.
plotDens2D()'s density heatmap,plotHeatmap()'s cell shading) are deliberately not theme-driven; they use a hardcoded, purpose-built palette viapal()instead (e.g.pal("red-black"),pal("Blues")). Neitherpalette(categorical) nortwin(a fixed pair) is the right semantic fit for an ordered, continuous scale – seepal()for the registry of named continuous palettes.barcol="grey80", border=NA. Default bar fill/border inplotBar().autoTitleFALSE. WithTRUE, plots called withmain = NULL(the default) get a title derived from the input, e.g."len ~ supp"forplotBox(len ~ supp, ToothGrowth); withFALSEthey get none. An explicitmainalways wins. Handy for interactive exploration or teaching:setTheme(list(autoTitle = TRUE)).styabs="abs.sty", perc="per.sty", num="num.sty", pval="pval.sty". Names offm()format styles (seestyles()) used for absolute counts, percentages, plain numbers, and p-values respectively.stampexpression(...)– unevaluated. The corner stamp text drawn by everystamp()/.withGraphicsState()call. Stored as an unevaluatedexpression()andeval()'d at draw time (not at theme-load or theme-set time), so it always reflects the current user and date rather than freezing whatever they were when the theme was defined or last changed. Default:"<username> / <YYYY-MM-DD>".
The .useTheme sentinel
Internally, a function argument that should follow the active theme
(rather than some fixed value) defaults to a dedicated sentinel object,
.useTheme, not to TRUE, FALSE, NA, or
NULL. Those four are frequently legitimate, explicit values in
their own right (e.g. grid = NULL commonly means "suppress the
grid" for a given function) - using any of them to also mean "no value
was given, defer to the theme" would make that case ambiguous. A
dedicated sentinel avoids the ambiguity entirely and keeps the
resolution logic a single, explicit equality check
(identical(x, .useTheme)) rather than an implicit, error-prone
guess based on data type.
Two small internal helpers resolve it:
-
.useThemeValue(value, ...)- for a simple value taken from a nested theme key, e.g.col <- .useThemeValue(col, "points", "col"). -
.resolveToggle(spec, themeValue)- for an on/off-style argument (such asgrid/box) that may also be aTRUE/FALSE/NA/NULL/list spec in its own right, used internally by.drawGrid()/.drawBox().
Some theme values require more than a simple key lookup to resolve
(e.g. building a color ramp from twin, or constructing a list of
point parameters from points); those are resolved with a small
inline identical(x, .useTheme) check directly in the consuming
function rather than forcing them through one of the two generic
helpers above. See e.g. plotCor()'s col argument or
plotDot()'s pch argument for worked examples.
How plotting functions consume the theme
.applyParFromDots()Applies
getTheme()$paras the lowest-precedencepar()pass, before the function's own defaults and the user's.....drawGrid(grid, defaults = list())/.drawBox(box, defaults = list())-
Generic dispatchers wrapping
graphics::grid()/graphics::box(). Resolve the.useThemesentinel, merge the theme's style values with any function-specificdefaults(e.g.plotBar()suppressing the axis-parallel grid direction vianx/ny), and dispatch viabedrock::callIf(). Not used by every function that draws a grid or frame: a few (plotCor(),plotHeatmap(),plotDot()) have grid/box geometry tied to exact data coordinates (e.g. half-integer cell boundaries) that doesn't matchgraphics::grid()'s axis-tick-based geometry: these resolve theme values directly viagetTheme()$grid/getTheme()$boxbut draw with their own clippedrect()/abline()calls instead. .withGraphicsState(expr, stamp = .useTheme, ...)Wraps a plotting function's body, restores
par()afterwards, and - afterexprhas run successfully - callsstamp()with the (possibly theme-resolved) corner stamp text/arguments.
Presets
setTheme() also accepts a single preset name (a string) instead
of a list, looked up in an internal preset registry
(.themePresets). No presets are currently registered; the
registry exists so named, complete theme variants (e.g. a monochrome or
high-contrast theme) can be added later without changing the
setTheme() interface.
See Also
pal() for the color palette registry,
fm() for the formatting styles referenced by sty,
stamp() for the corner stamp mechanism.
Examples
# inspect the active theme
getTheme()
# change only the qualitative palette for the rest of the session
setTheme(list(palette = "Set2"))
# change the accent color pair used for e.g. lm/loess fit lines
setTheme(list(twin = c("firebrick", "navy")))
# turn grid lines off package-wide (any .useTheme-driven grid argument
# everywhere now resolves to "off", unless a function overrides it)
setTheme(list(grid = FALSE))
# back to package defaults
resetTheme()
Plot Boxed Annotation
Description
The function can be used to add a title to a plot surrounded by a rectangular box. This is useful for plotting several plots in narrow distances.
Usage
titleRect(
label,
bg = "grey",
border = 1,
col = "black",
xjust = 0.5,
line = 2,
...
)
Arguments
label |
the main title |
bg |
the background color of the box. |
border |
the border color of the box |
col |
the font color of the title |
xjust |
the x-justification of the text. This can be |
line |
on which MARgin line, starting at 0 counting outwards |
... |
the dots are passed to the |
Value
nothing is returned
See Also
Other graphics.annotation:
barText(),
boxedText(),
colLegend(),
errBars(),
stamp(),
textLegend()
Examples
plot(pressure)
titleRect("pressure")
Render a matrix as an HTML table
Description
Converts a matrix (or vector) to a <table> HTML fragment, with
optional row/column headers, caption, per-column alignment and widths.
The result has class c("html", "character") (see
asHtml()) and prints as a formatted text table via
preview.html().
Usage
toHtmlTable(
m,
sepCol = FALSE,
caption = "",
bodyAlign = "center",
vAlign = "top",
width = NULL,
cellPadding = 3,
border = 0,
tableWidth = NA,
captionAlign = "center",
frame = TRUE,
rowNames = TRUE,
colNames = TRUE
)
Arguments
m |
a matrix or vector |
sepCol |
logical; if |
caption |
table caption text |
bodyAlign |
horizontal alignment of body cells
( |
vAlign |
vertical alignment of body cells (HTML |
width |
column width(s) (HTML |
cellPadding |
HTML |
border |
HTML |
tableWidth |
overall table width (HTML |
captionAlign |
horizontal alignment of the header row cells |
frame |
logical; if |
rowNames |
logical; render the row names as a leading header
column. Ignored when |
colNames |
logical; render the column names as a header row.
Ignored when |
Value
an object of class c("html", "character")
See Also
Other html:
asFileLink(),
asHtml(),
asImg(),
embedFile(),
escapeHtml(),
htmlNotation,
htmlSubscript,
preview(),
preview.html()
Examples
m <- matrix(c(12.3, 4.56, 7.8, 91.2), nrow = 2,
dimnames = list(c("a", "b"), c("mean", "sd")))
# the HTML fragment ...
(h <- toHtmlTable(m, caption = "Summary"))
# ... and its rendering as text
preview(h)
# formatted cells, right aligned, without the row names
preview(toHtmlTable(fm(m, digits = 1), rowNames = FALSE, bodyAlign = "right"))
Apply Geometric Transformations to Coordinates
Description
Applies scaling, rotation, and translation to a set of 2D coordinates. The transformations are applied in the following order:
Scaling
Rotation (see
rotate())Translation
Usage
transformXY(
x,
y = NULL,
translate = c(0, 0),
scale = c(1, 1),
theta = 0,
asp = 1
)
Arguments
x |
numeric vector of x coordinates, or an object coercible by
|
y |
numeric vector of y coordinates. Ignored if |
translate |
numeric vector of length 1 or 2 specifying translation
in x and y direction. Recycled if necessary. Default is |
scale |
numeric vector of length 1 or 2 specifying scaling factors
for x and y. Recycled if necessary. Default is |
theta |
rotation angle in radians. Default is |
asp |
aspect ratio adjustment passed to |
Details
This function is a convenience wrapper combining basic affine transformations.
Internally, it uses rotate() for rotation.
Value
A list with components x and y, as returned by
xy.coords().
See Also
Other geometry.transformation:
rotate()
Examples
x <- c(0, 1, 1, 0)
y <- c(0, 0, 1, 1)
# scale, rotate and translate a square
transformXY(x, y,
scale = 2,
theta = pi / 4,
translate = c(1, 1))
# matrix input
m <- cbind(x, y)
transformXY(m, scale = 0.5, theta = pi/6)
Get or Set Unit Attribute
Description
Retrieves or assigns a unit attribute to an R object.
Usage
unit(x)
unit(x) <- value
Arguments
x |
an R object. |
value |
A single character string specifying the unit, or |
Details
The unit is stored as a simple character string in the "unit" attribute.
This provides a lightweight mechanism for attaching unit metadata to objects,
without enforcing any automatic conversion or validation.
The setter does not validate whether the unit is physically meaningful.
Validation and conversion should be handled externally (e.g., via
a unit conversion engine such as ConvUnit7).
Assigning NULL removes the unit attribute.
Value
-
unit(x)returns the unit as a character string orNULL. -
unit(x) <- valuereturnsxwith updated unit attribute.
See Also
Other format:
convUnit(),
fm(),
fmCI(),
print.Unit(),
style()
Examples
x <- 10
unit(x) <- "m"
unit(x)
y <- 5
unit(y) <- "kg"
# remove unit
unit(y) <- NULL