如何在多个图表上获得最佳拟合线?

时间:2016-11-10 18:19:20

标签: r plot lm

我如何才能在这些图表中找到最合适的线条?随意更改我的代码或使用另一个库 - 这就像我遇到困难之前一样。谢谢!

exampledf<- data.frame(year=c("1999","1999","1999","1995","1995","1995"),npi=c(20,40,20,30,40,15),school=c("A","B","C","A","B","C"))
library(lattice)
library(car)
with(exampledf,
     xyplot(npi~year|school,xlab="Year",ylab="NPI",main="NPI measurements by school and year", aspect = "xy"),
     abline(lm(npi~year|school,data=exampledf))
)

enter image description here

使用xyplot的解决方案:

添加参数type=c("p","r")

参考here这会为每个图添加点和回归线

1 个答案:

答案 0 :(得分:1)

ggplot2怎么样? (注意,我在每个小组中添加了一个额外的点)

exampledf<- data.frame(year= rep(c("1999", "1995", "2005"), each = 3),
   npi=c(20,40,20, 30,40,15, 15, 15, 30),
   school=rep(c('A', "B", "C"), 3))

library(ggplot2)

ggplot(exampledf, aes(x = year, y = npi, group = school)) + 
    geom_point() +
    geom_smooth(method = "lm") +
    facet_wrap(~school)

enter image description here