Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plus sign between ggplot2 and other function (R) [duplicate]

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?

like image 882
mimic Avatar asked Jul 03 '16 04:07

mimic


1 Answers

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.

like image 66
Jonathan Carroll Avatar answered Sep 18 '22 16:09

Jonathan Carroll