Context and Question:
I want to add a legend to a lattice plot in R that shows the density of two groups.
I’ve changed the default colours to black and gray. However, the legend has not updated the colours.
- How can I get the lattice plot to use my updated colours in the legend?
- How can I control the position of the legend (I’d like to be able to place it inside the plot area)?
Working example:
set.seed(4444)
x1 <- rep("Group A", 50)
x2 <- rep("Group B", 50)
y1 <- rnorm(50, 0, 2)
y2 <- rnorm(50, 1, 2)
dtf <- data.frame(x=c(x1, x2), y =c(y1, y2))
print(densityplot(~y, groups=x, data=dtf,
pch=".",
cex=2,
col=c("black", "gray"),
auto.key=TRUE,
xlab="Y"))

The legend color is a well-known annoyance in lattice. It looks like it is difficult to correct, because Deepayan recommends simpleTheme as a solution. For positioning, see Josh’s answer.