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). I'd like R-squared in the format R^2 =, where R is italicised, and 2 is superscript.
Adding R-squared in this way on its own can be achieved on the following example using bquote
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?)
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. 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)
This seems as though it should be straightforward but I'm having no joy. Any help would be much appreciated, thanks.