Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...