13

I'm trying to get this example:

ggplot(mpg, aes(displ, hwy)) + geom_point()

Can somebody explain me what's going on here between these 2 functions?

Does ggplot2 overload "plus" operator? What is the result of summarizing these 2, and what is it assigned to? Is it R-specific feature, or ggplot2-specific? Is it kind of pipe?

mimic
  • 4,897
  • 7
  • 54
  • 93
  • 11
    It's not easy to find, but `help("+.gg")` has the information you want. I found out that `+.gg` exists by using `methods("+")` with ggplot2 loaded. – Rich Scriven Jul 03 '16 at 04:25
  • 6
    Yes and no; it's effectively a pipe (Hadley discovered/coauthored magrittr after ggplot2, and has said it's too late to change ggplot now), but it's actually adding to a ggplot object, which is not plotted until the call is complete. So yes, you can think of it as passing the `data` parameter between functions, but it's more useful to think of it as...additive. Wrap a plot in `ggplot_build` to get an idea of what the objects are inside. – alistaire Jul 03 '16 at 05:08

1 Answers1

5

The function definition that @Richard Scriven refers to in comment is defined in plot-construction.r, which might make it clearer. You'll need to go through the source to see exactly what those two (unexported) functions do (whether the LHS of the call is a theme or a ggplot object) but the names should give you a pretty good idea. The return value is e1 modified by "adding" e2.

"+.gg" <- function(e1, e2) {
  # Get the name of what was passed in as e2, and pass along so that it
  # can be displayed in error messages
  e2name <- deparse(substitute(e2))

  if      (is.theme(e1))  add_theme(e1, e2, e2name)
  else if (is.ggplot(e1)) add_ggplot(e1, e2, e2name)
}

So, yes, + is overloaded for objects inheriting class gg (all ggplot2 objects).

I think 'pipe' (@alistaire's comment) is a misleading analogy; this is very much in the style of the standard Ops group generic.

Jonathan Carroll
  • 3,897
  • 14
  • 34