R Normalize 然后在 R 中绘制两个直方图

R Normalize then plot two histograms together in R

我知道有几篇帖子询问如何将两个直方图并排绘制在一起(就像在一个图中,条形图彼此相邻)并在 R 中叠加以及如何标准化数据。按照我找到的建议,我可以执行其中一项,但不能同时执行这两项操作。

这是设置。 我有两个不同长度的数据框,想将每个 df 中对象的体积绘制为直方图。例如,数据帧 1 中有多少在 .1-.2 um^3 之间,并将其与数据帧 2 中有多少在 .1 和 .2 um^3 之间进行比较,依此类推。覆盖或并排会很好。

由于一个数据帧中的测量值比另一个数据帧多,显然我必须归一化,所以我使用:

read.csv(ctl)
read.csv(exp)
h1=hist(ctl$Volume....)
h2=hist(exp$Volume....

#to normalize#

h1$density=h1$counts/sum(h1$counts)*100
plot(h1,freq=FALSE....)
h2$density=h2$counts/sum(h2$counts)*100
plot(h2,freq=FALSE....)

现在我已经成功地使用这种方法覆盖了未规范化的数据:http://www.r-bloggers.com/overlapping-histogram-in-r/ and also with this method: plotting two histograms together

但我对如何叠加规范化数据感到困惑

ggplot2 使得绘制大小不等的组的归一化直方图变得相对简单。这是一个假数据的例子:

library(ggplot2)

# Fake data (two normal distributions)
set.seed(20)
dat1 = data.frame(x=rnorm(1000, 100, 10), group="A")
dat2 = data.frame(x=rnorm(2000, 120, 20), group="B")
dat = rbind(dat1, dat2)

ggplot(dat, aes(x, fill=group, colour=group)) +
  geom_histogram(breaks=seq(0,200,5), alpha=0.6, 
                 position="identity", lwd=0.2) +
  ggtitle("Unormalized")

ggplot(dat, aes(x, fill=group, colour=group)) +
  geom_histogram(aes(y=..density..), breaks=seq(0,200,5), alpha=0.6, 
                 position="identity", lwd=0.2) +
  ggtitle("Normalized")

如果你想制作叠加的密度图,你也可以这样做。 adjust 控制带宽。这已经默认标准化。

ggplot(dat, aes(x, fill=group, colour=group)) +
  geom_density(alpha=0.4, lwd=0.8, adjust=0.5) 

更新: 在回答您的评论时,应该使用以下代码。 (..density..)/sum(..density..) 导致两个直方图的总密度加起来为 1,并且每个单独组的总密度加起来为 0.5。因此,您必须乘以 2,以便将每个组的总密度分别归一化为 1。通常,您必须乘以 n,其中 n 是组数。这似乎有点笨拙,可能有更优雅的方法。

library(scales) # For percent_format()

ggplot(dat, aes(x, fill=group, colour=group)) +
  geom_histogram(aes(y=2*(..density..)/sum(..density..)), breaks=seq(0,200,5), alpha=0.6, 
                 position="identity", lwd=0.2) +
  scale_y_continuous(labels=percent_format())