R中的叠加直方图(首选ggplot2)

Ric*_*ron 4 plot r histogram ggplot2

我试图用ggplot2创建这样的分层直方图: 我想要创建的样式图

以下是我认为可行的一些数据和代码:

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)) 
Run Code Online (Sandbox Code Playgroud)

但我的代码产生了这个: 在此输入图像描述

谢谢!我更喜欢ggplot2(在我学习的时候,我认为我只是学习了普通的,可扩展的绘图语言),但我对任何事情都很开放.

Kev*_* L. 8

我相信这就是你要找的东西:

叠加直方图

请注意,我更改了您的治疗指标变量TRUE/FALSE而不是0/1,因为它需要是ggplot分裂的因素.这scale_alpha有点像黑客,因为它是连续变量,但据我所知,没有一个离散的模拟.

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))
Run Code Online (Sandbox Code Playgroud)