Overlaid histograms in R (preferably ggplot2)

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

Here is 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 study, I decided that I was just learning a common, extensible building language), but I am open to anything / everything.

+4
source share
3 answers

I believe this is what you are looking for:

Overlaid histograms

Note that I changed your processing indicator variable to TRUE/FALSE , not 0/1 , as this should be a factor for dividing ggplot into it. scale_alpha is a bit of a hack because it is for continuous variables, but as far as I can tell there is no discrete analogue.

 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)) 
+8
source

FWIW, I based on the answers above to get really close to the original histogram that I provided.

 data.3.t <- subset(data.3, treat == 1) data.3.c <- subset(data.3, treat == 0) fig.3 <- ggplot() fig.3 <- fig.3 + geom_histogram(data = data.3.t , binwidth = 0.05, aes(x = prop_score, linetype = treat.factor), fill = NA, colour = "black") fig.3 <- fig.3 + geom_histogram(data = data.3.c, binwidth = 0.05, aes(x = prop_score, linetype = treat.factor), fill = NA, colour = "black") fig.3 <- fig.3 + scale_linetype_manual(values = c(1,2)) fig.3 <- fig.3 + labs(x = "propensity score", linetype = "group") fig.3 <- fig.3 + theme_bw() 

Something like that: enter image description here

+2
source
 my.fig <- ggplot(data = my.data) + geom_histogram(binwidth = 0.05, aes(x = prop_score, position = identity, linetype=treat), fill="white", colour="black",alpha=0)+ scale_linetype_manual(values=c(1,2))+ theme_bw() 
+1
source

Source: https://habr.com/ru/post/1343958/


All Articles