在 ggplot 的注释中显示固定小数

display fixed decimals in ggplot's annotate

我需要在 ggplot 的注释中包含所有浮点数,以便在小数点分隔符后显示 3 位数字。但我遇到了这个问题:

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)

两者都生成只有一位小数的绘图。很明显,如果我更改为 parse = FALSE,那么绘图会带有正确的小数位数,但它的格式(很明显)与预期格式相去甚远。

除了硬引入文本之外,还有哪些其他选择可以实现这一点?

如果你给数字加上引号就可以了。

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)

在这里,我将 %0.3f 更改为 '%0.3f',从而得到字符串

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

因此,数字不再被解释为数值。 1.800 表示数字 1.8,'1.800' 表示字符串 1.800.