我正在尝试向显示以下内容的图添加简单的注释:“ R ^ 2:0.90”,其中2显示为指数。我遇到了问题,因为parse函数从我的R平方值中删除了结尾的0,但是我无法弄清楚如何将解析的字符串和未解析的字符串粘贴在一起。
R2 <- 0.90
R2.ann <- parse(text=(paste("R^2:", sprintf("%.2f", round(R2,2)), sep="")))
R2.ann <- paste(parse(text="R^2"), ": ", sprintf("%.2f", round(R2,2)), sep="")
# And other variations on this, using as.character() or separating the parts into individual variables
# Here is a simple ggplot that the annotation right in the middle
ggplot(data=data.frame(0,0), aes(x = 0, y = 0)) + geom_point(color="white") + annotate("text", label=R2.ann, x=0, y=0)
首先,您需要创建一个有效的?plotmath
表达式。由于需要用R对其进行解析,因此它必须是有效的表达式。您可以使用组合?plotmath
表达式中的数字和字符串*
。所以一个适当的表达是
expression(R^2 * ": * "0.1")
例如。我们可以bquote
用来插入您的实际价值。
bquote(R^2 * ": " * .(sprintf("%.2f", round(R2,2))))
但是annotate()
ggplot中的命令需要采用一个字符值,而不是表达式,因此我们可以deparse()
做到这一点。
R2.ann <- deparse(bquote(R^2 * ": " * .(sprintf("%.2f", round(R2,2)))))
然后在绘制时,需要告诉annotate()
它需要进行解析
ggplot(data=data.frame(0,0), aes(x = 0, y = 0)) +
geom_point(color="white") +
annotate("text", label=R2.ann, x=0, y=0, parse=TRUE)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句