[R] ggplot expressions

David Winsemius dwinsemius at comcast.net
Mon Mar 20 15:19:32 CET 2017

> On Mar 20, 2017, at 4:42 AM, Troels Ring <tring at gvdnet.dk> wrote:
> Dear friends - here is an example of something that I find annoying
> library(ggplot2)
> DDF <- data.frame(x=x<-seq(1,10),y=x^2)
> G <- ggplot(data=DDF,aes(x=x,y=y)) + geom_point()
> GG<-G+ylab(expression(paste("Total ",CO[2]," halved")))
> GG
> GG+annotate("text",x=5,y=50,label=expression(paste("Total ",CO[2]," halved")))
> On my system, R version 3.3.2 (2016-10-31) Windows - the third line produces the wanted formatting of CO2  with "2" lowered - while the last line produces an error  "invalid 'type' (expression) of argument" - with exactly the same string - how comes?
> Beautiful ggplot is not exactly low in documentation but finding the right stuff is not always easy (for me:-))

As the Posting Guide recommends, the question should include the complete text of the error message:

"Error in stats::complete.cases(df[, vars, drop = FALSE]) : 
  invalid 'type' (expression) of argument"

In this case, however I find that message completely opaque and the results of traceback() likewise uninformative, so going back to the help pages, always a good place to start, notice that the last example on `?annotate` is isomorphic to you problem, so try using the curiously unlisted `parse`-parameter to annotate. The parse parameter according to the documentation is being passed to `layer`, but `?layer` doesn't describe a parse parameter so I think it's a defect (somewhere) in the ggplot2 help pages.

GG + annotate("text", x=5, y=50, label = "Total~CO[2]~halved", parse=TRUE)

I have removed the call to `paste` since I find that it's use inhibits learning to use expressions most economically. I think it's better to use the tilde rather than assembling a mishmash of quoted and unquoted sub-expressions.


> Best wishes
> Troels Ring, MD
> Aalborg, Denmark
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA

More information about the R-help mailing list