facet_wrap的百分比直方图

时间:2018-10-07 16:00:57

标签: r ggplot2 histogram facet-wrap

我正在尝试将百分比直方图与facet_wrap组合在一起,但是百分比不是基于组而是所有数据来计算的。我希望每个直方图都显示一个组中的分布,而不是相对于所有人群。我知道可以绘制多个图并将它们与multiplot合并。

library(ggplot2)
library(scales)
library(dplyr)

set.seed(1)
df <- data.frame(age = runif(900, min = 10, max = 100),
                 group = rep(c("a", "b", "c", "d", "e", "f", "g", "h", "i"), 100))

tmp <- df %>%
  mutate(group = "ALL")

df <- rbind(df, tmp)

ggplot(df, aes(age)) + 
  geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 5) + 
  scale_y_continuous(labels = percent ) + 
  facet_wrap(~ group, ncol = 5) 

输出: output plot

2 个答案:

答案 0 :(得分:3)

尝试使用y = stat(density)(或ggplot2版本3.0.0之前的y = ..density..)而不是y = (..count..)/sum(..count..)

ggplot(df, aes(age, group = group)) + 
  geom_histogram(aes(y = stat(density) * 5), binwidth = 5) + 
  scale_y_continuous(labels = percent ) +
  facet_wrap(~ group, ncol = 5)

enter image description here

来自?geom_histogramm“计算变量”下的

  

密度:bin中点的密度,按比例缩放为1

我们乘以5(箱宽度),因为y轴是密度(面积积分为1),而不是百分比(高度总和为1),请参见Hadley's comment(感谢@MariuszSiatka )。

答案 1 :(得分:2)

虽然facet_wrap似乎没有在每个子集中运行特殊的geom_histogram百分比计算,但请考虑分别构建一个图列表,然后将它们网格排列在一起。

具体来说,调用by group 子集中运行ggplots,然后调用gridExtra::grid.arrange()(实际打包方法)以某种方式模仿facet_wrap

library(ggplot2)
library(scales)
library(gridExtra)

...

grp_plots <- by(df, df$group, function(sub){
  ggplot(sub, aes(age)) + 
    geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 5) + 
    scale_y_continuous(labels = percent ) + ggtitle(sub$group[[1]]) +
    theme(plot.title = element_text(hjust = 0.5))
})

grid.arrange(grobs = grp_plots, ncol=5)

Plot Output


但是,要避免重复使用y轴和x轴,请考虑在theme调用中有条件地设置by,假设您提前知道了您的组,并且他们的数量是合理的。

grp_plots <- by(df, df$group, function(sub){

  # BASE GRAPH
  p <- ggplot(sub, aes(age)) + 
    geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 5) + 
    scale_y_continuous(labels = percent ) + ggtitle(sub$group[[1]])

  # CONDITIONAL theme() CALLS
  if (sub$group[[1]] %in% c("a")) {
    p <- p + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_blank(), 
                  axis.text.x = element_blank(), axis.ticks.x = element_blank())
  }
  else if (sub$group[[1]] %in% c("f")) {
    p <- p + theme(plot.title = element_text(hjust = 0.5))
  }
  else if (sub$group[[1]] %in% c("b", "c", "d", "e")) {
    p <- p + theme(plot.title = element_text(hjust = 0.5), axis.title.y = element_blank(), 
                   axis.text.y = element_blank(), axis.ticks.y = element_blank(),
                   axis.title.x = element_blank(), axis.text.x = element_blank(), 
                   axis.ticks.x = element_blank())
  }
  else {
    p <- p + theme(plot.title = element_text(hjust = 0.5), axis.title.y = element_blank(), 
                   axis.text.y = element_blank(), axis.ticks.y = element_blank())
  }
  return(p)
})

grid.arrange(grobs=grp_plots, ncol=5)

Plot Output