user1885116
user1885116

Reputation: 1797

Different colour for different types of lines using xyplot

This is probably a very basic question, but i am struggling in Lattice in an xyplot where i plot both the curve as well as the regression line (type "r", type "l") to give each line a different colour.

I have basicaly tried the code below with the ?cars data set.

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

The problem is that it plots both lines, but both of them red....

Upvotes: 1

Views: 6550

Answers (2)

Matthew Lundberg
Matthew Lundberg

Reputation: 42689

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

Upvotes: 5

user1317221_G
user1317221_G

Reputation: 15461

Here is one way with 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

For the sake of it, personally I prefer to do these thinhs in 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

Upvotes: 4

Related Questions