display fixed decimals in ggplot's annotate

2.1k views Asked by At

I need to have all floating numbers in an annotation in ggplot to show 3 digits after the decimal separator. but I'm facing this problem:

require(ggplot2)
data(iris)
a <- 1.8
b <- 0.9

ggplot(iris, aes(Sepal.Length, Petal.Length))+
   geom_point()+
   annotate("text", 7, 3, 
            label = paste0("y == ", format(a, digits = 3, nsmall = 3), " %*%z^", 
                           format(b, digits = 3, nsmall = 3)), parse = TRUE)
ggplot(iris, aes(Sepal.Length, Petal.Length))+
 geom_point()+
 annotate("text", 7, 3,
          label = sprintf("y == %0.3f %%*%%z^ %0.3f", a,b), parse = TRUE)

both produce plots with only one decimal. It's clear that if I change to parse = FALSE, then the plot comes with the correct number of decimals, but its format is (quite obviously) far from the expected one.

Other than hard-introducing the text, what other options do exist to achieve this?

1

There are 1 answers

1
Sven Hohenstein On BEST ANSWER

It works if you add quotation marks to the numbers.

ggplot(iris, aes(Sepal.Length, Petal.Length))+
  geom_point()+
  annotate("text", 7, 3, label = sprintf("y == '%0.3f' %%*%%z^ '%0.3f'", a,b), parse = TRUE)

Here, I changed %0.3f to '%0.3f' resulting in the string

[1] "y == '1.800' %*%z^ '0.900'"

Due to this, the numbers are no longer interpreted as numercial values. While 1.800 represents the number 1.8, '1.800' represents the string 1.800.

enter image description here