Percentage histogram with facet_wrap

前端 未结 2 1727
孤街浪徒
孤街浪徒 2021-01-02 11:25

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

2条回答
  •  失恋的感觉
    2021-01-02 11:38

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

提交回复
热议问题