How to include updated line colors in a plot legend in R using a grid?

Context and Question:

I want to add a legend to the lattice graph in R, which shows the density of two groups. I changed the default colors to black and gray. However, the legend did not update the colors.

  • How can I make the grid graph use my updated colors in a legend?
  • How can I control the position of the legend (I would like to place it inside the chart 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")) 

enter image description here

+6
source share
2 answers

The color of the legend is a known annoyance in the grate. This seems to be hard to fix 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")) 
+7
source

There may be a more elegant solution, but it works quite well. Note that the corner= argument can be used to place the legend anywhere on the chart.

 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") 

enter image description here

+5
source

Source: https://habr.com/ru/post/903652/


All Articles