I am trying to create a layered histogram like this with ggplot2:
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:
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.
I believe this is what you are looking for:
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With