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.

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

Was it helpful?

Solution 2

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`

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

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top