R中的直方图图例

Histogram legend in R

我有一个直方图

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

我无法正确显示图例,黑色实心条、阴影条和红线与数据匹配(我知道密度线不正确,但包括在内以便有本例中的一行)。有人知道怎么做吗?

这是您要找的吗?

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

已编辑:包括具有适当值的角度和密度参数

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:根据评论的例子

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