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


Need Your Help

Remove checkbox from CheckBoxTree node

java swing jtree renderer jcheckbox

I'm using a CheckBoxTree component to get a special kind of JTree with checkboxes. However, I want to be able to have no checkbox on the high level nodes, because they should never be checked, they...

UIImageView setImage While UIScrollView is Scrolling

ios objective-c uiscrollview uiimageview

I'm trying to set the image property of a UIImageView while a UIScrollView is scrolling. It seems like the image sets just fine but it only will show up in the image view once scrolling completes....

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.