2013-01-08 69 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()'。 –