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

时间:2011-03-16 16:31:30

标签: r plot ggplot2 histogram

我正在尝试使用ggplot2创建这样的分层直方图: Style plot that I'd like to create

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

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)) 

但我的代码产生了这个: enter image description here

谢谢!我更喜欢ggplot2(在我学习的过程中,我认为我只是学习了常用的,可扩展的绘图语言),但我对所有事情都很开放。

3 个答案:

答案 0 :(得分:8)

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

Overlaid histograms

请注意,我将治疗指标变量更改为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))

答案 1 :(得分:2)

FWIW,我建立在上面的答案上,非常接近我提供的原始直方图。

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() 

这给出了这样的东西: enter image description here

答案 2 :(得分:1)

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()