Learn R Programming

ggplot2 (version 4.0.4)

Stat: Stats

Description

All stat_*() functions (like stat_bin()) return a layer that contains a Stat* object (like StatBin). The Stat* object is responsible for rendering the data in the plot.

Arguments

Details

Each of the Stat* objects is a ggproto() object, descended from the top-level Stat, and each implements various methods and fields. The object and its parameters are chaperoned by the Layer class.

To create a new type of Stat object, you typically will want to override one or more of the following:

  • The required_aes and default_aes fields.

  • One of the compute_layer(), compute_panel() or compute_group() functions. Typically it best to implement compute_group() and use the higher-up methods when there are substantial performance improvements to be gained.

  • The finish_layer() method

See Also

The new stats section of the online ggplot2 book..

Run vignette("extending-ggplot2"), in particular the "Creating a new stat" section.

Other Layer components: Geom, Layer-class, Position

Examples

Run this code
# Extending the class
StatKmeans <- ggproto(
  "StatKmeans", Stat,
  # Fields
  required_aes = c("x", "y"),
  # You can relate computed variables to aesthetics using `after_stat()`
  # in defaults
  default_aes = aes(colour = after_stat(cluster)),
  # Methods
  compute_panel = function(data, scales, k = 2L) {
    km <- kmeans(cbind(scale(data$x), scale(data$y)), centers = k)
    data$cluster <- factor(km$cluster)
    data
  }
)

# Building a constructor
stat_kmeans <- function(mapping = NULL, data = NULL, geom = "point",
                        position = "identity", ..., k = 2L, na.rm = FALSE,
                        show.legend = NA, inherit.aes = TRUE) {
  layer(
    mapping = mapping, data = data,
    geom = geom, stat = StatKmeans, position = position,
    show.legend = show.legend, inherit.aes = inherit.aes,
    params = list(na.rm = na.rm, k = k, ...)
  )
}

# Use new stat in plot
ggplot(mpg, aes(displ, hwy)) +
  stat_kmeans(k = 3)

Run the code above in your browser using DataLab