简体   繁体   English

情节传说中的R平方和n

[英]R-squared and n in plot legend

I would like a plot legend to contain both the R-squared value, as well as another value (the number of datapoints, n , in this case, but it's not specifically important). 我想一个情节图例包含R平方值,以及另一个值(数据点的数量, n ,在这种情况下,但它并不特别重要)。 I'd like R-squared in the format R ^2 =, where R is italicised, and 2 is superscript. 我希望R格式为R ^ 2 =,其中R是斜体,2是上标。

Adding R-squared in this way on its own can be achieved on the following example using bquote 在以下使用bquote示例中,可以通过这种方式自行添加R平方

DF <- data.frame(VAR1=rnorm(100), VAR2=rnorm(100))
with(DF, plot(VAR1, VAR2))
fit <- lm(VAR2 ~ VAR1, data=DF)
r2 <- summary(fit)$adj.r.squared
mylabel = bquote(italic(R)^2 == .(format(r2, digits = 2)))
legend("bottomright", legend = mylabel ) # display legend

Adding both the R-squared value and n can be achieved in the following way (with credit to @DirkEddelbuettel here How can I plot my R Squared value on my scatterplot using R? ) 添加R平方值和n可以通过以下方式实现(在此处获得@DirkEddelbuettel的信用我如何使用R在我的散点图上绘制我的R平方值?

legend("topleft", legend = c( paste("R2 =", format(r2, digits = 2)),
                              paste("n = ", nrow(DF)) ) )

However, I'm unable to find a way of modifying this to format the R ^2 in a way that doesn't also paste the call. 但是,我无法找到一种方法来修改它以便以不粘贴调用的方式格式化R ^ 2。 For example, 例如,

legend("topleft", legend = c( expression(paste(italic(R)^2, " = ", format(r2, digits = 2))),
                          paste("n = ", nrow(DF)) ) )

will successfuly format the R ^2 but also pastes format(r2, digits = 2) 将成功格式化R ^ 2,还会粘贴format(r2, digits = 2)

This seems as though it should be straightforward but I'm having no joy. 这似乎应该是直截了当的,但我没有快乐。 Any help would be much appreciated, thanks. 任何帮助将不胜感激,谢谢。

Here is a way to do it, using atop to split within several lines. 这是一种方法,使用atop在几行内分割。

# your code
DF <- data.frame(VAR1=rnorm(100), VAR2=rnorm(100))
with(DF, plot(VAR1, VAR2))
fit <- lm(VAR2 ~ VAR1, data=DF)
r2 <- summary(fit)$adj.r.squared
mylabel = bquote(italic(R)^2 == .(format(r2, digits = 2)))

# the legend
legend("topright", legend=bquote(atop(italic(R)^2 == .(format(r2, digits = 2)),"n" == .(nrow(DF)))),bty="n")

Note that I had to remove the box around the legend ( bty=n" ) as it is not well managed. For another solution involving mtext you may be interested in those two other post on stack and all links there: 请注意,我必须删除图例周围的框( bty=n" ),因为它管理得不好。对于涉及mtext另一个解决方案,您可能会对堆叠中的其他两个帖子以及所有链接感兴趣:

Expression and new line in plot labels 图标签中的表达式和新行

Line break in expression()? 表达式()中的换行符?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM