使用xyplot的不同类型的线的不同颜色

时间:2013-01-08 13:44:04

标签: r graph lattice

这可能是一个非常基本的问题,但是我在一个xyplot中在Lattice中苦苦挣扎,我在曲线和回归线(类型“r”,类型“l”)上绘制曲线,为每条线赋予不同的颜色

我已基本尝试使用?cars数据集创建以下代码。

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

问题在于它绘制了两条线,但它们都是红色的......

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

相关问题