处理 ggplot2 中的方面直方图的不同样本大小

Dealing with different sample sizes for facet histograms in ggplot2

我想在 ggplot2 中按年份制作堆叠 (facet_grid) 大小的直方图。这些年有不同的样本量。我无法让 ..density.. 为每个直方图 bin 生成正确的比例。所以,我一直在使用 ..count../(样本数量)。根据我对 stat 转换 ..count.. 的阅读,您不能对对象执行操作(例如 nrow(data))。如何获得这些具有不同样本量的堆叠直方图?下面代码中的格式将生成一个与报告的其他图形相匹配的图形,这就是为什么我想坚持使用 ggplot2,但也许还有其他包。这是一个例子:

d1 <- as.data.frame(round(rnorm(121, 86, 28), 0))
colnames(d1) <- "Length"
d1$Year <- "2015"

d2 <- as.data.frame(round(rnorm(86, 70, 32), 0))
colnames(d2) <- "Length"
d2$Year <- "2016"

D <- rbind(d1, d2)

ggplot(D, aes(x = Length)) +
  geom_histogram(aes(y = ..count../nrow(D)), 
                 breaks=seq(0, 160, by = 3), 
                 col="black", 
                 fill="grey48", 
                 alpha = .8)+
  labs(title = "Size by Year", x = "Length", y = "frequency") +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
  theme_bw() + 
  theme(text = element_text(size=16), 
        axis.text.y = element_text(size=12)) +
  geom_vline(aes(xintercept = 95.25), 
             colour = "red", size = 1.3)+
  facet_grid(Year ~ .)

这部分 ..count../nrow(D) 行不通,当我对它们进行分面时需要每年的样本量 facet_grid(Year ~ .)

这是您要找的吗?您没有指定使用 ..density.. 时出了什么问题,但似乎您只需要按 binwidth 进行缩放。 ..density.. 进行缩放,使条形总面积为 1,这意味着每个条形的高度为 ..count.. / (n * binwidth)。您只希望高度为 ..count.. / n,即 ..density.. * binwidth。所以手动设置 binwidth(无论如何你都应该这样做)并乘以它。

set.seed(1234)
d1 <- as.data.frame(round(rnorm(121, 86, 28), 0))
colnames(d1) <- "Length"
d1$Year <- "2015"

d2 <- as.data.frame(round(rnorm(86, 70, 32), 0))
colnames(d2) <- "Length"
d2$Year <- "2016"

D <- rbind(d1, d2)

library(ggplot2)
ggplot(D, aes(x = Length)) +
  geom_histogram(aes(y = ..density.. * 5), binwidth = 5) +
  geom_vline(aes(xintercept = 95.25), colour = "red", size = 1.3) +
  facet_grid(Year ~ .) +
  labs(title = "Size by Year", x = "Length", y = "frequency") +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
  theme_bw() +
  theme(
    text = element_text(size = 16),
    axis.text.y = element_text(size = 12)
  )

reprex package (v0.2.0) 创建于 2018-09-19。