user3489562
user3489562

Reputation: 249

Colouring a subset of data in Lattice plots R

I have plotted a xyplot in lattice of shellfish catch rates by year grouped by survey area using the below code:

xyplot(catch.rate ~ Year | Area, data, xlab = "Year", ylab = "Catch rate",
    col ="black", par.settings = list(strip.background=list(col="white")))

I have one year of data that I would like to highlight on the plot in a different colour (e.g. red). I created a subset of this data with:

subset <- grep("^0214A",data$Haul_ID,ignore.case=TRUE)

I have done something similar with the standard R plots using points before but as I am new to lattice and I am not sure how to do this using this package.

Upvotes: 1

Views: 444

Answers (1)

Martin Morgan
Martin Morgan

Reputation: 46866

For plots without conditioning variables, the col= argument accepts a vector parallel to the points being plotted, so for instance

xyplot(mpg~disp, mtcars, col=mtcars$cyl, pch=20, cex=4)

colors points by the number of cylinders. Maybe you'd do

cols=c("red", "green")[grepl("^0214A", data$Haul_ID, ignore.case=TRUE) + 1L]

For plots with conditioning variables, one can write a panel function that accepts the col vector and subscripts, an index into the data describing the rows currently being plotted. Pass the arguments to the panel function to panel.xyplot(), adjusting the color of each point to reflect the subset of data in the panel. Here's the panel function

panel <- function(..., col, subscripts) {
    panel.xyplot(..., col=col[subscripts])
}

and in action

xyplot(mpg ~ disp | factor(cyl), mtcars, col=mtcars$cyl, 
       panel=panel, pch=20, cex=4)

Upvotes: 1

Related Questions