3

The short version: How would I make this contrived code plot a proper greek beta character AND the rest of the label string, with the space and the less than character and the numbers formatted as typed?

library("ggplot2")
df<-data.frame(a=1:15,b=6:20)
ggplot(data=df, aes(x=a,y=b)) + geom_point() +
       geom_text(x=5,y=4,label="beta=1.00 p<0.0001", parse=TRUE)

If I leave out the ", parse=TRUE" argument, the string works great, but won't give me a real greek beta. If I leave it in, all hell breaks loose.


The long version (and why I can't find a duplicate): I finally discovered in How to use Greek symbols in ggplot2? that methods for placing greek characters on a ggplot depends upon where you're putting them. Since I am using geom_text to force strings of text onto the body of the plot, my attempts to use expression(beta) have failed and I recently started using the parse argument mentioned above. I came across How can I add alpha-numeric AND greek characters to geom_text() in ggplot?, which I thought was my answer, but fixing the "space" resulted in extra parentheses popping in, "=" replaced by a comma, and loss of formatting for all of my previously formatted text numerics.

A link to a guide for using the parse argument, and how to make sense of what seems to me to be completely unintuitive would be very helpful to me, and probably future R users ending up here. Many searches have been fruitless.

Community
  • 1
  • 1
mightypile
  • 7,589
  • 3
  • 37
  • 42

1 Answers1

11

This should do it:

g <- ggplot(data=df, aes(x=a,y=b)) + geom_point()
g + annotate("text", x=5,y=4,parse=TRUE, label="beta==1.00 * ' p<0.0001'")

It's a matter of splitting the label with single quotes to the side of the whitespace and connecting two label bits with *. You also need the == for equals to.

enter image description here

jalapic
  • 13,792
  • 8
  • 57
  • 87
  • Great information! Thanks! Two additions from my experimenting with it: Single quotes around the '1.00' allow me to keep my sigfigs. And I noticed that this works with both annotate() and geom_text(), other answers suggest reasons for using annotate() for this particular need. Any suggestions on a guide to this grammar? I can now make this example work, but still don't understand it for future needs that may arise. – mightypile Feb 24 '15 at 02:38
  • 2
    not sure about a definitive guide to grammar - but this plotmath helpfile is useful for learning what syntax to use: https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/plotmath.html – jalapic Feb 24 '15 at 02:50
  • 1
    `label="beta==1.00 * ~italic(p)~ ' < 0.0001'"` for italic p – CrunchyTopping Sep 27 '19 at 19:19