Skip to content

Overlay Histogram

5 messages · arun, R. Michael Weylandt, Li Li +1 more

#
HI,

#These links 


http://stackoverflow.com/questions/8545035/scatterplot-with-marginal-histograms-in-ggplot2
http://stackoverflow.com/questions/11022675/rotate-histogram-in-r-or-overlay-a-density-in-a-barplot
#? might be helpful for you.
A.K.



----- Original Message -----
From: li li <hannah.hlx at gmail.com>
To: r-help <r-help at r-project.org>
Cc: 
Sent: Monday, August 6, 2012 3:40 PM
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.
#
See

example(layout)

for one idea. I think you might also want to look into rug plots.

Best,
Michael
On Mon, Aug 6, 2012 at 2:40 PM, li li <hannah.hlx at gmail.com> wrote:
#
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
____________________________________________________________
FREE ONLINE PHOTOSHARING - Share your photos online with your friends and family!
Visit http://www.inbox.com/photosharing to find out more!