2

I have a histogram of the form

rm(list = ls())
set.seed(1)
x1 <- rnorm(100, mean=1)
x2 <- rnorm(100)
hist(x1, col="black", ylim=c(0,30), xlim=range(pretty(range(x1, x2))), xlab="x-axis label", ylab="y-axis label", main="", cex.lab=1.3, las=1)
hist(x2, xlab="", ylab="", main="", ylim=c(0,yhigh), xlim=c(0,.05), density = 20, col= "gray", axes=F, add=TRUE, lty=1)
lines(density(x2, from = 0, to = max(x2)), col ="firebrick", lwd = 1.5)
legend("topright", c("group1", "group2", "density"), lty=c(1,1, 1), bty = "n")

I am having trouble getting the legend to appear correctly, with a solid black bar, a hatched bar, and a red line to match the data (I know the density line is not right, but including so as to have a line in this example). Anybody know how to do this?

marcel
  • 389
  • 1
  • 8
  • 21

2 Answers2

1
legend("topright", c("group1", "group2", "density"), 
    lty=c(1,2, 1), bty = "n", 
    fill=c("black", "gray", "firebrick"))

Edited: Include angle and density arguments with the appropriate values

legend("topright", c("group1", "group2", "density"), lty=c(1,2, 1), 
    bty = "n", angle = c(0, 45, 0), density = c(100, 30, 100),
    fill=c("black", "gray", "firebrick"))

Edited2: Example according to the commentary

legend("topright", c("group1", "group2"), 
    bty = "n", angle = c(0, 45), density = c(100, 30),
    fill=c("black", "gray"))

legend(2.7, 28, "density", lty = 1, bty = "n", lwd=2, col = "firebrick")
PereG
  • 1,796
  • 2
  • 22
  • 23
0

Is this what you are looking for?

legend("topright", 
       c("group1", "group2", "density"), 
       lty=c(1, 2, 1), 
       col=c("black","gray","firebrick"), 
       bty = "n")
vtortola
  • 34,709
  • 29
  • 161
  • 263
  • The solution before is a bit closer because the symbols for groups 1 and 2 in the legend are bars rather than lines. However that one did not get the hatched fill. – marcel Sep 13 '15 at 00:40