Reputation: 1797
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
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'
)
Upvotes: 5
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")))
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)
Upvotes: 4