Search code examples
rplotlegendlegend-properties

How to combine filled squares and plot symbols in a legend in R?


I made a boxplot and added the mean as a point. In the legend I'd like to put the filled squares corresponding to the boxes. Nest to the boxes I want to add a symbol corresponding to the mean. However, my attempts were unsuccessfully. Any help?

A <- 1:10
B <- 2:11
DF <- data.frame(A, B)

boxplot(DF, col = gray.colors(2), ylim = c(0,20))
points(1, mean(A), pch = 3, col = "red")
points(2, mean(B), pch = 3, col = "red")
legend("topleft", fill = c(gray.colors(2), 0), legend = c("A", "B", "Mean"), horiz = T,
       pch = 3, col = "red")

enter image description here


Solution

  • This should be sortable by including default values or NA values for the earlier boxes' pch= arguments, and vice-versa for the mean indicator. Like so:

    legend("topleft", fill = c(gray.colors(2), 0), border=c("black","black",NA),
           legend = c("A", "B", "mean"), horiz = TRUE, pch = c(NA,NA,3), col=c(NA,NA,"red"))