Reputation: 34947
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.
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"))
Upvotes: 7
Views: 2008
Reputation: 10215
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.
print(densityplot(~y, groups=x, data=dtf,
pch=".",
cex=2,
par.settings=simpleTheme(col=c("gray","black")),
auto.key=TRUE,
xlab="Y"))
Upvotes: 8
Reputation: 162451
There might be a more elegant solution, but this works well enough. Notice that the corner=
argument can be used to place the legend anywhere inside the plot.
densityplot(~y, groups = x, data = dtf,
pch = ".",
cex = 2,
col = c("black", "gray"),
par.settings = list(superpose.line = list(col=c("black", "grey"))),
auto.key = list(corner = c(0.95, 0.95)),
xlab = "Y")
Upvotes: 6