Rilcon42 Rilcon42 - 1 year ago 75
R Question

How to get lines of best fit on multiple graphs?

How would I get a seperate line of best fit on each of these graphs? Feel free to change my code or use another library- this was just as far as I got before I got stuck. Thanks!

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"))
xyplot(npi~year|school,xlab="Year",ylab="NPI",main="NPI measurements by school and year", aspect = "xy"),

enter image description here

Solution using xyplot:

add the parameter

reference here This adds both the points and the regression line to each plot

Answer Source

How about this, with ggplot2? (note, I added an additional point to each panel)

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))


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

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download