Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is ggplot2 plus operator defined?

The + usually throws non-numeric argument to binary operator when provided with something other than a number. But it works with ggplot2, pasting the plot together. At the same time, it retains its usual function outside of the context of ggplot2 (e.g. as an arithmetic or formula operator), so its ggplot2 version is not in conflict with either of these.

I wish to understand how to make the + behave this way. Browsing the ggplot2 github repo, I have found function definitions for +.gg and %+% but it did not make things clearer for me.

I would be happy with a pointer to the code in ggplot2 package that does this, or a generalized explanation of how this is done.

like image 982
jakub Avatar asked Nov 06 '16 15:11

jakub


People also ask

What does %>% mean in ggplot?

the %>% is a pipe operator that is actually part of the dplyr library (along with the filter function) not from the ggplot2 library. To sample 1%, there is a sample_frac function in the dplyr library. It would be something like (df %>% sample_frac(0.01))

What is the difference between ggplot and ggplot2?

You may notice that we sometimes reference 'ggplot2' and sometimes 'ggplot'. To clarify, 'ggplot2' is the name of the most recent version of the package. However, any time we call the function itself, it's just called 'ggplot'.


1 Answers

If you dissect +.gg we have:

> ggplot2:::`+.gg`
function (e1, e2) 
{
  e2name <- deparse(substitute(e2))
  if (is.theme(e1)) 
    add_theme(e1, e2, e2name)
  else if (is.ggplot(e1)) 
    add_ggplot(e1, e2, e2name)
}

Besides, add_theme, what you're interested in is is add_ggplot which can be accessed with ggplot2:::add_ggplot. The latter - a long yet very organized function - reveals more "cascading" functions to dispatch what's meant to be added.

That being said, R "knows" when using "+" on an object of class gg which function to apply (because of S3 classes). You can find the starting point in ggplot2 GitHub repos, in the ggproto.R on which I think most of ggplot2 behaviour depends on.

Is that what you're looking for?

like image 71
Vincent Bonhomme Avatar answered Oct 05 '22 11:10

Vincent Bonhomme