diff --git a/NAMESPACE b/NAMESPACE index 21b0aa84ed..10e876622b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -44,6 +44,7 @@ S3method(fortify,tbl_df) S3method(ggplot,"function") S3method(ggplot,default) S3method(ggplot_add,"NULL") +S3method(ggplot_add,"function") S3method(ggplot_add,Coord) S3method(ggplot_add,Facet) S3method(ggplot_add,Layer) diff --git a/R/plot-construction.r b/R/plot-construction.r index c8ebca0378..65aa986b83 100644 --- a/R/plot-construction.r +++ b/R/plot-construction.r @@ -162,3 +162,20 @@ ggplot_add.Layer <- function(object, plot, object_name) { plot$labels <- defaults(plot$labels, new_labels) plot } +#' @export +ggplot_add.function <- function(object, plot, object_name) { + # Allow examples such as: + # ggplot(mtcars, aes(x = disp, y = mpg)) + geom_point + # just as dplyr allows both of: + # 5 %>% sin() + # 5 %>% sin + env <- parent.frame() + object <- do.call(object, args = list(), envir = env) + # prevent any confusing cycling. + if(is.function(object)) { + stop("ggplot_add.function, right hand side evaluated to another function.", + call. = FALSE) + } + # re-dispatch + ggplot_add(object, plot, object_name) +}