rggplot2histogramfacet-wrap

Percentage histogram with facet_wrap


I am trying to combine percentage histogram with facet_wrap, but the percentages are not calculated based on group but all data. I would like each histogram to show distribution in a group, not relative to all population. I know it is possible to do several plots and combine them with 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: output plot


Solution

  • Try with y = stat(density) (or y = ..density.. prior to ggplot2 version 3.0.0) instead of 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

    from ?geom_histogram under "Computed variables"

    density : density of points in bin, scaled to integrate to 1

    We multiply by 5 (the bin width) because the y-axis is a density (the area integrates to 1), not a percentage (the heights sum to 1), see Hadley's comment (thanks to @MariuszSiatka).