# How to add a 2nd y-axis for a density plot superimposed on a histogram in R?

I have a histogram shown below, and I have added 2 density plots on top of that. It corresponds to the 2 classes that make up the data.

I want to add a 2nd y-axis on the right, but having same height as the 1st y-axis, so that the height of the density plots do not look so small. **The relative heights of the 2 density plots must to directly comparable, such that their combined area is 1**

## Answers

z <- rnorm(100,.3,.2) hist(z, xlab="", ylab="", main="", yaxt="n") par(new=TRUE) plot(density(z), xlab="", ylab="", main="", xaxt="n", yaxt="n") axis(2, ...) # plug in the relevant values for `at` and `labels` axis(4, ...) # plug in the relevant values for `at` and `labels`

If you use ggplot2 you can use geom_density(aes(y=..scaled..)) and geom_histogram(aes(y = ..ndensity)) to scale similarly

eg

x <- rnorm(400, 10, 5) y <- rnorm(400, -10, 5) dd <- rbind(data.frame(value = x, id = 'x'), data.frame(value = y, id = 'y')) ggplot(dd, aes(x=value)) + geom_histogram(aes(y=..ndensity..)) + geom_density(aes(colour = id, y = ..scaled..))