While there are several SO posts on how to use percents scaled within each facet of a bar chart, I don't see any that show how to do that in a histogram. Is it possible to so do?
Here are two posts I researched:
SO post 1: Obtaining Percent Scales Reflective of Individual Facets with ggplot2 Last answer on this post indicates solution no longer working on newer versions of ggplot2 and suggests use of stat_count() but does not give example.
SO post2: percentage on y lab in a faceted ggplot barchart?
The following code creates a histogram with the percents scaled across all facets (i.e. sum of all bars is 100%) rather than within each facet.
ggplot(iris, aes(Sepal.Width, y=(..count..)/sum(..count..))) + geom_histogram(bins=2) +
facet_grid(~Species) + scale_y_continuous(labels = scales::percent)
Is there a way to scale within each facet? If not, what would be an efficient strategy of converting to bar chart? If I had to go that route, I could use cut()
to create a factor of bin indicators, then calculate bin frequencies within each level of facet variable (using dplyr::count()
?), then use geom_bar()
. Seems convoluted. I suspect there is a geom_histogram()
solution.
Thanks for any thoughts ...