density_auto {ggdist}R Documentation

Automatic density estimator

Description

Density estimator that picks density_bounded() or density_unbounded() depending on trim. Supports automatic partial function application.

Usage

density_auto(
  x,
  weights = NULL,
  n = 512,
  bandwidth = "nrd0",
  adjust = 1,
  kernel = "gaussian",
  trim = FALSE,
  ...
)

Arguments

x

numeric vector containing a sample to compute a density estimate for.

weights

optional numeric vector of weights to apply to x.

n

numeric: the number of grid points to evaluate the density estimator at.

bandwidth

bandwidth of the density estimator. One of:

  • a numeric: the bandwidth, as the standard deviation of the kernel

  • a function: a function taking x (the sample) and returning the bandwidth

  • a string: the suffix of the name of a function starting with "bw." that will be used to determine the bandwidth. See bw.nrd0() for a list.

adjust

numeric: the bandwidth for the density estimator is multiplied by this value. See stats::density().

kernel

string: the smoothing kernel to be used. This must partially match one of "gaussian", "rectangular", "triangular", "epanechnikov", "biweight", "cosine", or "optcosine". See stats::density().

trim

Should the density estimate be trimmed to the bounds of the data? If TRUE, uses density_bounded(), if FALSE, uses density_unbounded().

...

Additional arguments passed to density_bounded() or density_unbounded().

Value

An object of class "density", mimicking the output format of stats:density(), with the following components:

This allows existing methods (like print() and plot()) to work if desired. This output format (and in particular, the x and y components) is also the format expected by the density argument of the stat_slabinterval() and the smooth_ family of functions.

See Also

Other density estimators: density_bounded(), density_unbounded()

Examples

library(distributional)
library(dplyr)
library(ggplot2)

set.seed(123)
x = rbeta(5000, 1, 3)

# here we'll use the same data as above, but pick either density_bounded()
# or density_unbounded() (which is equivalent to stats::density()). Notice
# how the bounded density (green) is biased near the boundary of the support,
# while the unbounded density is not.
data.frame(x) %>%
  ggplot() +
  stat_slab(
    aes(xdist = dist), data = data.frame(dist = dist_beta(1, 3)),
    alpha = 0.25
  ) +
  stat_slab(aes(x), density = "auto", trim = TRUE, fill = NA, color = "#d95f02", alpha = 0.5) +
  stat_slab(aes(x), density = "auto", trim = FALSE, fill = NA, color = "#1b9e77", alpha = 0.5) +
  scale_thickness_shared() +
  theme_ggdist()

[Package ggdist version 3.2.1 Index]