質問

Apologies if this has been asked before; I couldn't locate a similar question besides this one (How can I plot my R Squared value on my scatterplot using R?). It was helpful in demonstrating the right way to call the R2 value itself.

My problem is that I am unable to get the "R2" to display properly, i.e. with the 2 as a superscript.

Using this code, I get the correctly-formatted R2, but the value is on the next line.

x <- 1:100
y <- 1:100
fit <- lm(y~x)
plot(x, y)
abline(lm(y~x))
legend("topleft", c(expression(paste("R"^2, "=")), 
       format(summary(fit)$adj.r.squared, digits=3)))

If I put the format(summary(fit)$adj.r.squared command within paste or expression, it (predictably) prints format(summary(fit)$adj.r.squared in the legend.

How to I get around this problem?

Thank you!

役に立ちましたか?

解決

One way to do it is to use bquote, and wrap any code that requires evaluation in .(), as suggested by @GGrothendieck here.

legend('topleft', bty='n',
       as.expression(bquote(R^2==.(format(summary(fit)$adj.r.squared, 
                                          digits=3)))))

See also Uwe's Automation of Mathematical Annotation in Plots R Help Desk.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top