Home > OS >  How to add means of each x level in a regression plot?
How to add means of each x level in a regression plot?

Time:03-27

I am plotting a linear regression fit for the Loblolly data in R and trying to add each mean y for each x level. My code is below:

 plot(Loblolly$height~Loblolly$age, xlab = "Age", ylab = "Height", main = "Loblolly Data")
    lob.fit <- lm(Loblolly$height~Loblolly$age)
    lob.sum <- summary(lob.fit)
    str(lob.sum)
    abline(lob.fit)

This is probably a really easy question with a really easy answer but I don't know how to add the means. When I google all that shows up is ggplot and I'm not supposed to be using that. Any help?

CodePudding user response:

As @AndroMine stated in comments, you could use aggregate in points to get the means. Choose a nice pch= such as "-", give it a col=or and increase the size of the cex=. Note that the functions you use have a data= argument, so you don't have to keep typing Loblolly$.

plot(height ~ age, Loblolly, xlab="Age", ylab="Height", main="Loblolly Data")
abline(lm(height ~ age, Loblolly))
points(aggregate(height ~ age, Loblolly, mean), pch='-', cex=4, col=4)

enter image description here

  • Related