[R] Adding info from summary(lm(...)) to plot

Marc Schwartz marc_schwartz at comcast.net
Sun Dec 9 20:33:13 CET 2007


On Sun, 2007-12-09 at 19:15 +0000, Ted.Harding at manchester.ac.uk wrote:
> Hi Folks,
> 
> Say I have 2 continuous variables X,Y.
> 
> I can of course plot (X,Y) with
> 
>   plot(X,Y,pch="+",col="blue")
> 
> say, and add the regression line from lm(Y~X)
> by extracting the coefficients 'a' of Intercept
> and 'b' of X from Y.lm <- lm(Y~X).
> 
> Now, however, I want to have not only a general
> explanatory title such as
> 
>   main="Plot of Y against X"
> 
> but also (and ideally just under the main title
> and above the figure region of the plot) the
> result of
> 
>   round(summary(Y.lm)[[4]],digits=3)
> 
> exactly as shown below:
> 
>             Estimate Std. Error t value Pr(>|t|)
> (Intercept)   78.636      0.273 287.902    0.000
> X             -0.074      0.029  -2.527    0.012
> 
> It would also be OK to have it as a "subtitle"
> below the xlabel (which by default is X" in this case).
> 
> I've been trying to work out how to so this simply,
> but without much success. I can see a complicated
> way, which involves binding the row and column names,
> and the values, of the above output, using paste()
> along with "\n" at suitable places, but I'd like to
> have something much less intricate than that!
> 
> I'd also like to be able to integrate the solution
> nicely with the main title (or the X label) so that
> there's no overlap.
> 
> Any suggestions?
> 
> with thanks,
> Ted.

Ted, 

For plotting the fitted regression line, you can use:

  abline(ModelObject)

rather than extracting the coefs, etc.

See ?abline for more information.  There are also examples
in ?predict.lm using matplot()/matlines() for adding the
confidence/prediction intervals.

In terms of adding the model summary table, you might want to consider
doing this within a legend box using a monospace font. There was a
thread on this a couple of years back on r-help:

  http://finzi.psych.upenn.edu/R/Rhelp02a/archive/58410.html

You may wish to review the full thread to get a sense for the evolution
of the solutions posed.

HTH,

Marc Schwartz



More information about the R-help mailing list