Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlaid histograms in R (ggplot2 preferred)

I am trying to create a layered histogram like this with ggplot2: Style plot that I'd like to create

Here are some data and code that I thought would work:

my.data <- data.frame(treat = rep(c(0, 1), 100), prop_score = runif(2 * 100))
my.data <- transform(my.data, treat = ifelse(treat == 1, "treatment", "control"))
my.data <- transform(my.data, treat = as.factor(treat))
my.fig <- ggplot() + geom_histogram(data = my.data, binwidth = 0.05, alpha = 0.01, aes(x = prop_score, linetype = treat, position = identity)) 

But my code produces this: enter image description here

Thanks! I would prefer ggplot2 (while I'm learning, I figured I just learn the common, extensible plotting language), but I'm open to anything/everything.

like image 957
Richard Herron Avatar asked Dec 22 '22 16:12

Richard Herron


1 Answers

I believe this is what you are looking for:

Overlaid histograms

Note that I changed your treatment indicator variable to be TRUE/FALSE rather than 0/1, since it needs to be a factor for ggplot to split on it. The scale_alpha is a bit of a hack because it's for continuous variables, but there isn't a discrete analogue as far as I can tell.

library('ggplot2')
my.data <- data.frame(treat = rep(c(FALSE, TRUE), 100), prop_score = runif(2 * 100))
ggplot(my.data) +
  geom_histogram(binwidth = 0.05
                 , aes(  x = prop_score
                       , alpha = treat
                       , linetype = treat)
                 , colour="black"
                 , fill="white"
                 , position="stack") +
  scale_alpha(limits = c(1, 0))
like image 158
Kevin L. Avatar answered Jan 20 '23 07:01

Kevin L.