tags:

views:

112

answers:

2

Hi all. This seems a simple question, so I hope its a simple answer. I am plotting my points and fitting a linear model, which I can do OK. I then want to plot some summary statistics, for example the R Squared value, on the plot also. I can only seem to get the R Squared value at the command line. Any advice; do I need to be looking at ggplot or anything else? Thanks in advance.

#Does the plot
plot(df$VAR1, df$VAR2)
#Adds the line
abline(lm(df$VAR2~df$VAR1), col="red")
#Shows stats on command line
summary(lm(df$VAR2~df$VAR1))
+4  A: 

You can abuse legend() because it has the handy logical placement:

R> DF <- data.frame(VAR1=rnorm(100), VAR2=rnorm(100))
R> with(DF, plot(VAR1, VAR2))
R> abline(fit <- lm(VAR2 ~ VAR1, data=DF), col='red')
R> legend("topright", bty="n", legend=paste("R2 is", 
+         format(summary(fit)$adj.r.squared, digits=4)))

Here bty="n" suppresses the box, and you need format() to shorten the display. Other text() is good, as are arguments main= and sub= to plot().

Dirk Eddelbuettel
Thanks for the quick response. Seems to work, don't think I would have thought of that in a hurry!
phrozenpenguin
Feel free to accept this as the answer :)
Dirk Eddelbuettel
Apologies - still getting used to how this all works. I think thats accepted now..
phrozenpenguin
No apology needed. At some point each one of us was new here, and we're all learning together.
Dirk Eddelbuettel
+4  A: 

The text function places text into the current plot, it is one option for adding the r-squared value to a plot. Also look at the grconvertX and grconvertY functions for ways to find the location to place the text.

The corner.label and emptyspace functions in the plotrix package may also help.

Greg Snow
Thanks for the alternative option. I'm already used to using legend so will stick with that for now.
phrozenpenguin