marcel
marcel

Reputation: 409

Histogram legend in R

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?

Upvotes: 2

Views: 9446

Answers (2)

PereG
PereG

Reputation: 1846

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

Upvotes: 1

vtortola
vtortola

Reputation: 35905

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

Upvotes: 0

Related Questions