jakub jakub - 1 year ago 115
R Question

How is ggplot2 plus operator defined?


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
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.

Answer Source

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, the we see that 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.

Is that what you're looking for?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download