简体   繁体   中英

R: adding multiple regression lines and loess curve to plot

mod = lm(iris$Petal.Length ~ iris$Petal.Width + iris$Species)
plot(iris$Petal.Length ~ iris$Petal.Width, col = iris$Species)
abline(mod)

在此处输入图片说明

Here I'm stratifying Species and I want to plot 3 regression lines, one for each species. abline(mod) seems to only add one line only. Also, what if I wanted to add LOESS curve?

A ggplot one-liner:

library(ggplot2)

ggplot(iris, aes(Petal.Width, Petal.Length, color=Species)) + geom_point() + geom_smooth(method='lm', formula=y~x)

Leave out the arguments to geom_smooth() and you would get the LOESS line. However, the data here are so scant that this fails.

mod = lm(iris$Petal.Length ~ iris$Petal.Width + iris$Species)
plot(iris$Petal.Length ~ iris$Petal.Width, col = iris$Species)
abline(coefficients(mod)[1], coefficients(mod)[2])
abline(coefficients(mod)[1], coefficients(mod)[3])
abline(coefficients(mod)[1], coefficients(mod)[4])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM