mu1 = 1
mu2 = 1
sd1 = 0.5
sd2 = 1
n = 80
set.seed(42)
data1 = rnorm(n, mean = mu1, sd = sd1)
data2 = rnorm(n, mean = mu2, sd = sd2)
par(mar = c(2, 0, 0, 0))
# Set up the histogram with transparency
hist(data1, breaks = 10, col = adjustcolor(2, alpha.f = 0.5), border = 2, axes = FALSE,
xlim = c(min(data1, data2), max(data1, data2)),
main = "", xlab = "Value", ylab = "Frequency")
# Add second histogram
hist(data2, breaks = 20, col = adjustcolor(4, alpha.f = 0.5), border = 4, add = TRUE)
# Add vertical dashed lines for means
xbar1 = mean(data1)
xbar2 = mean(data2)
abline(v = xbar1, col = 2, lty = 2, lwd = 3)
abline(v = xbar2, col = 4, lty = 2, lwd = 3)
# Add legend
legend("topleft", legend = c("Sample 1", "Sample 2"),
fill = c(adjustcolor(2, alpha.f = 0.5), adjustcolor(4, alpha.f = 0.5)),
border = c(2, 4), bty = "n")
axis(1, at = xbar1, labels = expression(bar(x)[1]), col = 2, col.axis = 2)
axis(1, at = xbar2, labels = expression(bar(x)[2]), col = 4, col.axis = 4, lwd = 3)
Comment
Note that the slightly different numbers is due to rounding. You can get the exact numbers using the following code: