Skip to content

Commit 6d2ed6d

Browse files
authored
Extra documentation for ggplot_add() (#5968)
1 parent c9dce8a commit 6d2ed6d

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

R/plot-construction.R

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,32 @@ add_ggplot <- function(p, object, objectname) {
8484
#' @param object_name The name of the object to add
8585
#'
8686
#' @return A modified ggplot object
87+
#' @details
88+
#' Custom methods for `ggplot_add()` are intended to update the `plot` variable
89+
#' using information from a custom `object`. This can become convenient when
90+
#' writing extensions that don't build on the pre-existing grammar like
91+
#' layers, facets, coords and themes. The `ggplot_add()` function is never
92+
#' intended to be used directly, but it is triggered when an object is added
93+
#' to a plot via the `+` operator. Please note that the full `plot` object is
94+
#' exposed at this point, which comes with the responsibility of returning
95+
#' the plot intact.
8796
#'
8897
#' @keywords internal
8998
#' @export
99+
#' @examples
100+
#' # making a new method for the generic
101+
#' # in this example, we apply a text element to the text theme setting
102+
#' ggplot_add.element_text <- function(object, plot, object_name) {
103+
#' plot + theme(text = object)
104+
#' }
105+
#'
106+
#' # we can now use `+` to add our object to a plot
107+
#' ggplot(mpg, aes(displ, cty)) +
108+
#' geom_point() +
109+
#' element_text(colour = "red")
110+
#'
111+
#' # clean-up
112+
#' rm(ggplot_add.element_text)
90113
ggplot_add <- function(object, plot, object_name) {
91114
UseMethod("ggplot_add")
92115
}
@@ -152,7 +175,7 @@ ggplot_add.Facet <- function(object, plot, object_name) {
152175
#' @export
153176
ggplot_add.list <- function(object, plot, object_name) {
154177
for (o in object) {
155-
plot <- plot %+% o
178+
plot <- ggplot_add(o, plot, object_name)
156179
}
157180
plot
158181
}

man/ggplot_add.Rd

Lines changed: 25 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)