ggplot_add: Add custom objects to ggplot

View source: R/plot-construction.R

ggplot_addR Documentation

Add custom objects to ggplot

Description

This generic allows you to add your own methods for adding custom objects to a ggplot with +.gg.

Usage

ggplot_add(object, plot, object_name)

Arguments

object

An object to add to the plot

plot

The ggplot object to add object to

object_name

The name of the object to add

Details

Custom methods for ggplot_add() are intended to update the plot variable using information from a custom object. This can become convenient when writing extensions that don't build on the pre-existing grammar like layers, facets, coords and themes. The ggplot_add() function is never intended to be used directly, but it is triggered when an object is added to a plot via the + operator. Please note that the full plot object is exposed at this point, which comes with the responsibility of returning the plot intact.

Value

A modified ggplot object

Examples

# making a new method for the generic
# in this example, we apply a text element to the text theme setting
ggplot_add.element_text <- function(object, plot, object_name) {
  plot + theme(text = object)
}

# we can now use `+` to add our object to a plot
ggplot(mpg, aes(displ, cty)) +
  geom_point() +
  element_text(colour = "red")

# clean-up
rm(ggplot_add.element_text)

tidyverse/ggplot2 documentation built on Jan. 29, 2025, 6:53 a.m.