2013-01-08 62 views
1

這可能是一個非常基本的問題,但我在xyplot中的萊迪思掙扎,其中我繪製曲線以及迴歸線(類型「r」,類型「l 「)爲每一行賦予不同的顏色。使用xyplot不同類型的線的不同顏色

我有basicaly嘗試下面的代碼與?cars數據集。

xyplot(speed ~ dist, data=cars, type=c("r", "l"), 
     col=c("red", "black"), 
     auto.key=list(lines=TRUE)) 

的問題是,它畫出兩條線,但他們兩人的紅色....

+5

請讓你的例子可重複性。 –

回答

4

這裏是latticeExtra一個辦法:

df <- data.frame(x=1:10,y=c(10,9,8,1,3,4,6,7,8,10)) 

library(lattice) 
library(latticeExtra) 

xyplot(y ~ x, data=df, type=c("r"),col=c("gray")) + 
as.layer(xyplot(y ~ x, data=df, type=c("l"),col=c("blue"))) 

enter image description here

對於爲此,我個人比較喜歡在ggplot2

library(ggplot2) 
ggplot(df,aes(x=x,y=y)) + geom_line(colour="blue") + 
stat_smooth(method=lm,colour="black",se=FALSE) 

enter image description here

5
xyplot(speed ~ dist, data=cars, 
     panel=function(x, y, col, ...) { 
     panel.xyplot(x, y, col='red', ...) 
     panel.abline(lm(y~x), col='blue') 
     }, 
     type='l' 
) 

enter image description here

+0

+1就是這樣 –

+0

或者只是'panel.lines()'和'panel.lmline()'。 –