7

I need to annotate a location on a ggplot2 plot with a line that contains both a (real) greek letter and a number rounded to 2 decimal places. My problem arises because I want to display the decimal places even if they are both zero. Unfortunately, the parse = T setting in annotate converts the string "1.00" into "1". Here's a specific example:

alpha_num <- "1.00"
p <- ggplot(data.frame(x=1,y=1,label=paste0("alpha == ", alpha_num)))
p <- p + geom_text(aes(x,y,label=label), parse = TRUE, size = 30)

The code above produces the following plot:annotate is parsing out my zeros

How do I get alpha_num displayed in its entirety?

  • Kind of a duplicate of [this post](http://stackoverflow.com/questions/25108062/how-to-write-after-decimal-zero-in-ggplot-geom-text) but the answer below is much better. – m-dz Mar 29 '17 at 21:19

1 Answers1

10

You can do it with the use of deparse.

So your code looks like this

alpha_num <- "1.00"
p <- ggplot(data.frame(x=1,y=1,label=paste0("alpha == ", alpha_num)))
# Use deparse in label
p <- p + geom_text(aes(x,y,label=paste0("alpha == ", deparse(alpha_num))), parse = TRUE, size = 30)
p  

And the output is:

enter image description here

Miha
  • 2,559
  • 2
  • 19
  • 34
  • 1
    So much better than [here](http://stackoverflow.com/questions/25108062/how-to-write-after-decimal-zero-in-ggplot-geom-text)! – m-dz Mar 29 '17 at 21:18
  • 1
    what if the object to deparse is a vector? you will not only get your zeros back, but also the full vector with all its elements. – schotti Dec 09 '21 at 11:24