I would like to create a histogram where the y-axis shows the percentage per facet in ggplot2. I have seen several similar questions but some answers seem outdated or they show the percentage of all observations rather than per facet.
I tried this:
library(ggplot2)
library(scales)
ggplot(mtcars, aes(mpg))+
facet_grid(cyl ~ am)+
stat_count(aes(y=..prop..)) +
theme_bw()+
scale_y_continuous(labels = percent_format())
Which seems to work, except that the binwidth is not fixed. Facets with few observations have large bars.
How could I fix the binwidth?
EDIT: Solution adapted from ACNB I overlooked that before and I just saw that Andrey Kolyadin was quicker to provide a more concise solution.
binwidth <- 1
mtcars.stats <- mtcars %>%
group_by(cyl, am) %>%
mutate(bin = cut(mpg, breaks=seq(0,35, binwidth),
labels = seq(0 + binwidth, 35, binwidth)-(binwidth/2)),
n = n()) %>%
group_by(cyl, am, bin) %>%
summarise(p = n()/n[1]) %>%
ungroup() %>%
mutate(bin = as.numeric(as.character(bin)))
ggplot(mtcars.stats, aes(x = bin, y= p)) +
geom_col() +
facet_grid(cyl~am)+
theme_bw()+
scale_y_continuous(labels = percent_format())