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`
How to add a 2nd y-axis for a density plot superimposed on a histogram in R?
-
14-04-2022 - |
Question
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
Solution 2
OTHER TIPS
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..))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow