2016-11-10 86 views
0

我將如何在這些圖表上得到最適合的單獨線條?隨意更改我的代碼或使用另一個庫 - 這就像我在被卡住之前一樣。謝謝!如何在多個圖表上獲得最佳擬合線條?

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這增加了兩個點和迴歸線每個小區

+0

所以,你的代碼只有每學年兩個數據點。只有兩點,你不能有最適合的線。你想只用點線連接點嗎? –

+0

或'panel.abline'可能http://stackoverflow.com/questions/11949766/how-to-add-abline-with-lattice-xyplot-function –

+0

這只是一個簡單的例子 - 我的實際數據集要大得多 – Rilcon42

回答

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

+0

你介意包括一條最適合的代碼嗎?我的實際數據集遠大於每個面板2個點,並且我不熟悉ggplot – Rilcon42

+0

檢查編輯。我每年都增加一個附加點。另外,如果你想消除擬合線上的錯誤,你可以使用'geom_smooth(method =「lm」,se = FALSE)'而不是那裏的東西。 –