stat_moments: Displaying skew/kurtosis text in plots

stat_momentsR Documentation

Displaying skew/kurtosis text in plots

Description

stat_moments() summarises the data supplied to the x-axis, and draws text that displays the skewness and/or kurtosis of the data, with a variety of options. This is almost chiefly meant to be used in conjunction with a density plot, such as ggplot2::geom_density() or ggplot2::stat_density(). Since this object is returning text, it needs to be given coordinates on where to be placed. It requires the aesthetics xpos and ypos (see geom_abs_text()), which are coordinates (from 0-1) relative to the panel/facet panel the text is to be displayed in.

Usage

stat_moments(
  mapping = NULL,
  data = NULL,
  ...,
  geom = c("abs_text", "abs_label"),
  moment = c("skewness", "kurtosis", "both"),
  sig = FALSE,
  excess_kurtosis = FALSE,
  digits = 1,
  alternative = c("less", "greater", "two.sided"),
  inherit.aes = TRUE,
  parse = FALSE
)

Arguments

mapping, data, ..., inherit.aes, parse

See ggplot2::geom_text() for details.

geom

Determines which geom to use, geom_abs_text() or geom_abs_label(). By default, it uses geom_abs_text().

moment

A string determining which moment to display. Can be one of three values: "skewness", "kurtosis", or "both", which displays both moments.

sig

A logical; if true, will test the skewness for significance using moments::agostino.test(), i.e., the D'Agostino test of skewness. Significance will be indicated via asterisks.

excess_kurtosis

A logical; if TRUE, kurtosis will be expressed as "excess" kurtosis (i.e., kurtosis - 3, as 3 is the kurtosis of a normal distribution). If kurtosis is not displayed, this will be ignored.

digits

The number of digits after the decimal place to display for the moment values.

alternative

A string specifying the alternative hypothesis for the D'Agostino test. Must be one of "less" (default) "two.sided" or "greater". You can specify just the initial letter. If sig = FALSE, this will be ignored.

Examples

make_log_normal <- function(n, mu, sd, name) {
  log_mu <- log(mu)
  df <- data.frame(x=exp(rnorm(n, log_mu, sd=sd)))
  df$Name <- name
  df
}

new_df <- rbind(make_log_normal(1000, 100, 1, "Distr1"),
                make_log_normal(1000, 500, 0.3, "Distr2"),
                make_log_normal(1000, 900, 0.5, "Distr3"))

ggplot(new_df, aes(x=x, color=Name)) +
  geom_density() +
  facet_wrap(~Name, scales="free") +
  stat_moments(aes(xpos=0.5, ypos=0.75),
               sig = TRUE,
               moment = "both",
               fontface="bold") +
  theme_bw()


burchill/zplyr documentation built on Feb. 2, 2023, 11:01 a.m.