Learn R Programming

ggplot2 (version 4.0.1)

Geom: Geoms

Description

All geom_*() functions (like geom_point()) return a layer that contains a Geom* object (like GeomPoint). The Geom* object is responsible for rendering the data in the plot.

Arguments

Details

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

Compared to Stat and Position, Geom is a little different because the execution of the setup and compute functions is split up. setup_data runs before position adjustments, and draw_layer() is not run until render time, much later.

When creating a new Geom class, you may want to consider override one or more of the following:

  • The required_aes and default_aes fields.

  • The setup_data() and setup_params() functions.

  • Either the draw_panel() or draw_group() function.

  • The draw_key field.

See Also

The new geoms section of the online ggplot2 book.

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

Other Layer components: Layer-class, Position, Stat

Examples

Run this code
# Extending the class
GeomSimplePoint <- ggproto(
  "GeomSimplePoint", Geom,
  # Fields
  required_aes = c("x", "y"),
  draw_key     = draw_key_point,
  # Methods
  draw_panel = function(data, panel_params, coord) {
    data <- coord$transform(data, panel_params)
    grid::pointsGrob(data$x, data$y)
  }
)

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

# Use new geom in plot
ggplot(mpg, aes(displ, hwy)) +
  geom_simple_point()

Run the code above in your browser using DataLab