[R] Overlay Histogram

John Kane jrkrideau at inbox.com
Tue Aug 7 17:04:17 CEST 2012


I cannot see any obvious way to do this.  Ben Gunter's suggestion re layout makes sense.  Here is a version using grid and ggplot2.  Note I shamelessly stole code to due it.


library(ggplot2)
library(grid)

dd <- data.frame(x =  rnorm(1000, 10, 10), 
                   y =  rnorm(1000, 3, 20))
#  From https://stat.ethz.ch/pipermail/r-help/2011-June/280588.html

p1  <-  ggplot(dd, aes(x=x)) +
	geom_histogram(aes(y=..density..), fill="red", colour="black")+
	geom_density(colour="black", adjust=4) +
	opts(title="Normal Random Sample")

p2  <-  ggplot(dd, aes(x=y)) +
	geom_histogram(aes(y=..density..), fill="blue", colour="black")+
	geom_density(colour="black", adjust=4) +
	opts(title="Normal Random Sample") +
        coord_flip()

# From StackOverflow http://stackoverflow.com/questions/9490482/combined-plot-of-ggplot2-not-in-a-single-plot-using-par-or-layout-functio

# this simplifies the vp statement 
# otherwise we would have to use something like
# print(plot5 , vp = viewport(layout.pos.row = 2, layout.pos.col = 1:2))  
# and so on for the rest of the plots.
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)

grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))
print(p1, vp = vplayout(1, 1))   
print(p2, vp = vplayout(2, 1))




John Kane
Kingston ON Canada


> -----Original Message-----
> From: hannah.hlx at gmail.com
> Sent: Mon, 6 Aug 2012 15:40:55 -0400
> To: r-help at r-project.org
> Subject: [R] Overlay Histogram
> 
> Dear all,
>   For two sets of random variables, say, x <-  rnorm(1000, 10, 10) and  y
> <- rnorm(1000. 3, 20).
> Is there any way to overlay the histograms (and density curves) of x and
> y
> on the plot of y vs. x?
> The histogram of x is on the x axis and that of y is on the y axis.
>   The density curve here is to approximate the shape of the distribution
> and does not have to have area 1.
>    Thank you in advance.
>       Hannah
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

____________________________________________________________
FREE ONLINE PHOTOSHARING - Share your photos online with your friends and family!
Visit http://www.inbox.com/photosharing to find out more!



More information about the R-help mailing list