rggplot2

Stop parsing out zeros after decimals in ggplot2's annotate


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?


Solution

  • 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