Search code examples
rhistogramdensity-plot

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.

histogram 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


Solution

  • 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`