Statistic stat_correlation() applies stats::cor.test()
respecting grouping with method = "pearson" default but alternatively
using "kendall" or "spearman" methods. It adds textual labels
to a plot.
Usage
stat_correlation(
mapping = NULL,
data = NULL,
geom = "text_npc",
position = "identity",
...,
method = "pearson",
n.min = 2L,
alternative = "two.sided",
exact = NULL,
r.conf.level = ifelse(method == "pearson", 0.95, NA),
continuity = FALSE,
fit.seed = NA,
small.r = getOption("ggpmisc.small.r", default = FALSE),
small.p = getOption("ggpmisc.small.p", default = FALSE),
coef.keep.zeros = TRUE,
r.digits = 2,
t.digits = 3,
p.digits = 3,
CI.brackets = c("[", "]"),
label.x = "left",
label.y = "top",
hstep = 0,
vstep = NULL,
output.type = NULL,
boot.R = ifelse(method == "pearson", 0, 999),
na.rm = FALSE,
parse = NULL,
show.legend = FALSE,
inherit.aes = TRUE
)Arguments
- mapping
The aesthetic mapping, usually constructed with
aes(). Only needs to be set at the layer level if you are overriding the plot defaults.- data
A layer specific dataset, only needed if you want to override the plot defaults.
- geom
The geometric object to use display the data
- position
The position adjustment to use for overlapping points on this layer.
- ...
other arguments passed on to
layer. This can include aesthetics whose values you want to set, not map. Seelayerfor more details.- method
character One of "pearson", "kendall" or "spearman".
- n.min
integer Minimum number of distinct values in the explanatory variable (on the rhs of formula) for fitting to the attempted.
- alternative
character One of "two.sided", "less" or "greater".
- exact
logical Whether an exact p-value should be computed. Used for Kendall's tau and Spearman's rho.
- r.conf.level
numeric Confidence level for the returned confidence interval. If set to
NAcomputation of CI is skipped.- continuity
logical If TRUE , a continuity correction is used for Kendall's tau and Spearman's rho when not computed exactly.
- fit.seed
RNG seed argument passed to
set.seed(). Defaults toNA, indicating thatset.seed()should not be called.- small.r, small.p
logical Flags to switch use of lower case r and p for coefficient of correlation (only for
method = "pearson") and p-value.- coef.keep.zeros
logical Keep or drop trailing zeros when formatting the correlation coefficients and t-value, z-value or S-value (see note below).
- r.digits, t.digits, p.digits
integer Number of digits after the decimal point to use for R, r.squared, tau or rho and P-value in labels. If
Inf, use exponential notation with three decimal places.- CI.brackets
character vector of length 2. The opening and closing brackets used for the CI label.
- label.x, label.y
numericwith range 0..1 "normalized parent coordinates" (npc units) or character if usinggeom_text_npc()orgeom_label_npc(). If usinggeom_text()orgeom_label()numeric in native data units. If too short they will be recycled.- hstep, vstep
numeric in npc units, the horizontal and vertical step used between labels for different groups.
- output.type
character One of "expression", "text", "markdown", "marquee", "latex", "latex.eqn", "latex.deqn" or "numeric".
- boot.R
interger The number of bootstrap resamples. Set to zero for no bootstrap estimates for the CI.
- na.rm
a logical indicating whether NA values should be stripped before the computation proceeds.
- parse
logical Passed to the geom. If
TRUE, the labels will be parsed into expressions and displayed as described inplotmath. Default isTRUEifoutput.type = "expression"andFALSEotherwise.- show.legend
logical. Should this layer be included in the legends?
NA, the default, includes if any aesthetics are mapped.FALSEnever includes, andTRUEalways includes.- inherit.aes
If
FALSE, overrides the default aesthetics, rather than combining with them. This is most useful for helper functions that define both data and aesthetics and shouldn't inherit behaviour from the default plot specification, e.g.borders.
Details
stat_correlation() can be used to annotate a plot with the
correlation coefficient and the outcome of its test of significance. It
supports Pearson, Kendall and Spearman methods to compute correlation. It
is implemented as a wrapper on cor.test().
stat_correlation() generates labels as R expressions by default, but
LaTeX (package 'xdvir' or the TikZ graphic device), markdown ('ggtext' and
'marquee') and plain text are also supported, as well as numeric values for
user-generated text labels. The character labels include the symbol
describing the quantity together with the numeric value. For the confidence
interval (CI) the default is to follow the APA recommendation of using
square brackets. As the CI is computed by bootstrapping, fit.seed if
different to NA immediately before this computation.
The default argument used for output.type is guessed from the name
of the geometry. The default argument for parse is set based on
output-type, but if labels that need parsing are formatted from
numeric output within a call to aes(), or if the name of a
geom is not recognized, it can be necessary to override this default.
A ggplot statistic receives as data a data frame that is not the one
passed as argument by the user, but instead a data frame with the variables
mapped to aesthetics, named according to the aesthetics. cor.test()
is always applied to the variables mapped to the x and y
aesthetics, so the scales used for x and y should both be
continuous scales rather than discrete.
Note
Currently coef.keep.zeros is ignored, with trailing zeros always
retained in the character labels returned but not protected from
being dropped by R when these character strings are parsed into
plotmath expressions (i.e., when output.type = "expression").
Computed variables
If output.type is "numeric" the returned
tibble contains the columns listed below with variations depending on the
method. If the model fit function used does not return a value, the
value returned is NA_real_.
- x,npcx
x position
- y,npcy
y position
- r, and cor, tau or rho
numeric values for correlation coefficient estimates
- t.value and its df, z.value or S.value
numeric values for statistic estimates
- p.value, n
numeric values.
- r.conf.level
numeric value, as fraction of one.
- r.confint.low
Confidence interval limit for
r.- r.confint.high
Confidence interval limit for
r.- grp.label
Set according to mapping in
aes.- method.label
Set according
methodused.- method, test
character values
If output.type different from "numeric" the returned tibble contains
in addition to the columns listed above those listed below. If a numeric
value is missing the corresponding label is set to character(0L).
- r.label, and cor.label, tau.label or rho.label
Correlation coefficient as a character string.
- t.value.label, z.value.label or S.value.label
t-value and degrees of freedom, z-value or S-value as a character string.
- p.value.label
P-value for test against zero, as a character string.
- r.confint.label, and cor.conint.label, tau.confint.label or rho.confint.label
Confidence interval for
r(only withmethod = "pearson").- n.label
Number of observations used in the fit, as a character string.
- grp.label
Set according to mapping in
aes, as a character string.
Position of labels
When data are grouped by mapping a factor to an aesthetic, e.g.,
colour, shape and/or linetype the model is fitted
separately to each group, and for each group a whole set of labels is
generated. If the argument passed to label.y is a vector of length
1, this value determines the position of the equation and/or other labels
for the first group, and the positions of the labels for the remaining
groups are generated by adding vspace based on the group number.
If the argument passed to label.y is a vector of length > 1, it is
used unchanged, possibly extended by recycling, ignoring vstep.
If the labels are rotated by 90 degrees then the automatic stepping is
best based on hstep with vstep = 0. Similarly as described
above, if label.x is a vector of length > 1, it is
used unchanged, possibly extended by recycling, ignoring hstep.
When using facets and with a grouping that does not repeat in each panel,
the automatic positioning in most cases will not be the desired one. Manual
positioning using a vector of length > 1 for label.x and/or
label.y is the currently available workaround.
Output types
The formatting of character strings to be displayed in plots are marked as mathematical equations. Depending on the geom used, the mark-up needs to be encoded differently, or in some cases mark-up not applied.
"expression"The labels are encoded as character strings to be parsed into R's plotmath expressions.
"LaTeX", "TeX", "tikz", "latex"The labels are encoded as 'LaTeX' maths equations, without the "fences" for switching in math mode.
"latex.eqn"Same as
"latex"but enclosed in single$, i.e., as in-line maths."latex.deqn"Same as
"latex"but enclosed in double$$, i.e., as display maths."markdown"The labels are encoded as character strings using markdown syntax, with some embedded HTML.
"marquee"The labels are encoded as character strings using markdown syntax, with 'marquee' supported spans.
"text"The labels are plain ASCII character strings.
"numeric"No labels are generated. This value is accepted by the statistics, but not by the label formatting functions.
NULLThe value used depends on the argument passed to
geom.
If geom = "latex" (package 'xdvir') the output type used is
"latex.eqn". If geom = "richtext" (package 'ggtext') or
geom = "textbox" (package 'ggtext') the output type used is
"markdown". If geom = "marquee" (package 'marquee') the output
type used is "marquee". For all other values of geom the default
is "expression". Invalid values as argument trigger an error.
Which variables are available for mapping?
Computed variables and
their names can vary depending on the method used to fit a model or
the output.type in use. They can also depend for a given
method on other arguments passed when fitting a model or extracting
estimates and other computed values. In many cases, when values are not
available, the variables are filled with NA values.
In the statistics returning formatted strings for use as annotations, a
message is issued by default in interactive R sessions, listing the short
names for available formatted labels as recognized by functions
use_label() and f_use_label(), except when
output.type = "numeric" is passed, in which case the names of all
variables accessible by after_stat() within a call to aes()
are listed. This default ("nicknames") can be changed by setting R
option "ggpmisc.stat.vars.message" to one of "names",
"colnames" or "none".
In the statistics that plot a prediction or more generally mainly return
numeric variables, a message is issued by default in interactive R
sessions, listing the names of all variables accessible by
after_stat() within a call to aes() with at least some
non-missing values. This default ("colnames") can be changed by
setting R option "ggpmisc.stat.vars.message" to "none".
To explore the whole returned data frame for a given input we suggest the
use of geom_debug().
See also
cor.test() for details on the computations.
Aesthetics
stat_correlation() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:
| • | x | |
| • | y | |
| • | group | → inferred |
| • | grp.label | |
| • | hjust | → "inward" |
| • | label | → after_stat(r.label) |
| • | npcx | → after_stat(npcx) |
| • | npcy | → after_stat(npcy) |
| • | vjust | → "inward" |
Learn more about setting these aesthetics in vignette("ggplot2-specs").
Examples
# generate artificial data
set.seed(4321)
x <- (1:100) / 10
y <- x + rnorm(length(x))
my.data <- data.frame(x = x,
y = y,
y.desc = - y,
group = c("A", "B"))
# by default only R is displayed
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation()
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(small.r = TRUE)
ggplot(my.data, aes(x, y.desc)) +
geom_point() +
stat_correlation(label.x = "right")
# non-default methods
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(method = "kendall")
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(method = "spearman")
# use_label() can map a user selected label
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(use_label("R2"))
# use_label() can assemble and map a combined label
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(use_label("R", "P", "n", "method"))
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(use_label("R", "R.CI"))
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(use_label("R", "R.CI"),
r.conf.level = 0.95)
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(use_label("R", "R.CI"),
method = "kendall",
r.conf.level = 0.95)
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(use_label("R", "R.CI"),
method = "spearman",
r.conf.level = 0.95)
# f_use_label() provides additional flexibility
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(
f_use_label("R", "R.CI",
format = "\"Estimate: \"*%s*\" with confidence \"*%s"),
method = "spearman", r.conf.level = 0.95)
# manually assemble and map a specific label using paste() and aes()
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(aes(label =
after_stat(
paste(r.label, p.value.label, n.label,
sep = "*\", \"*"))))
# manually format and map a specific label using sprintf() and aes()
ggplot(my.data, aes(x, y)) +
geom_point() +
stat_correlation(aes(label =
after_stat(
sprintf("%s*\" with \"*%s*\" for \"*%s",
r.label, p.value.label, t.value.label))))
