Pav*_*ive 2 printf r annotate string-formatting ggplot2
我需要在注释中包含所有浮点数,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)
Run Code Online (Sandbox Code Playgroud)
都生成只有一位小数的图.很明显,如果我改为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)
Run Code Online (Sandbox Code Playgroud)
在这里,我改变了%0.3f对'%0.3f'生成字符串
[1] "y == '1.800' %*%z^ '0.900'"
Run Code Online (Sandbox Code Playgroud)
因此,这些数字不再被解释为商业价值.虽然1.800代表数字1.8,但'1.800'代表字符串1.800.