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
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)
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).