如何叠加先前使用ggplot2创建的直方图?

时间:2016-07-05 21:52:31

标签: r ggplot2 histogram

我需要从数据框创建不同的直方图。目前我正在使用此循环生成单独的直方图

一个例子:

df<-matrix(NA,2000,5)
df[,1]<-rnorm(2000,1,1)
df[,2]<-rnorm(2000,2,1)
df[,3]<-rnorm(2000,3,1)
df[,4]<-rnorm(2000,4,1)
df[,5]<-rnorm(2000,5,1)
df<-data.frame(df)

colnames(df) <- c("HB1",   "HB2", "HB3","HB4",  'HB5')

循环:

out<-list()
for (i in 1:5){   x = df[,i]
   out[[i]] <- ggplot(data.frame(x), aes(x)) +
                 geom_histogram(aes(y=..count../sum(..count..)), fill="red",
                   lwd=0.9, breaks=seq(0,5,0.1), col=("black"), alpha=I(.9)) +
                   labs(x=expression(d["HB"]), y="Frequency")
   grid.arrange(out[[i]],  ncol=1)
}

输出是5个这样的数字:

enter image description here

但现在我想做一个比较重叠所有这些。 这个数字是我真正想要的:

enter image description here

提前致谢

1 个答案:

答案 0 :(得分:1)

使用tidyr::gather重塑数据,然后使用填充美学和'position =“标识”'

df2 <- tidyr::gather(df)
head(df2)
#  key     value
#1 HB1 0.7493090
#2 HB1 2.5475796
#3 HB1 0.7756661
#4 HB1 1.2562534
#5 HB1 0.2757356
#6 HB1 2.4831947

ggplot(df2, aes(x = value, fill = key)) + 
  geom_histogram(aes(y=..count../sum(..count..)), breaks=seq(0,5,0.1), alpha=.6, position = "identity") +
  labs(x=expression(d["HB"]), y="Frequency")  

要尝试密度图,而eipi10指出可能更容易理解,请使用

ggplot(df2, aes(x = value, fill = key)) + 
  geom_density(alpha=.6) +
  labs(x=expression(d["HB"]), y="Frequency")