0

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

Solution using xyplot:

add the parameter type=c("p","r")

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

Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • So your code only has two data points per school. You can't have a line of best fit with only two points. Do you want to just connect the points with a line? – Daniel Anderson Nov 10 '16 at 18:24
  • or `panel.abline` possibly http://stackoverflow.com/questions/11949766/how-to-add-abline-with-lattice-xyplot-function – Hack-R Nov 10 '16 at 18:25
  • This is simply a minimal example- my actual dataset is much larger – Rilcon42 Nov 10 '16 at 18:28

1 Answers1

1

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

library(ggplot2)

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

enter image description here

Daniel Anderson
  • 2,394
  • 13
  • 26
  • Would you mind including the code for a line of best-fit. My actual dataset is much larger than 2 points per panel, and I am not familiar with ggplot – Rilcon42 Nov 10 '16 at 18:30
  • Check out the edit. I added an additional point to each year. Also, if you wanted to remove the error around the fitted line you could just use `geom_smooth(method = "lm", se = FALSE)` instead of what's up there. – Daniel Anderson Nov 10 '16 at 18:37