I want to create a population pyramid with ggplot2. This question was asked before, but I believe the solution must be far simpler.
test <- (data.frame(v=rnorm(1000), g=c('M','F')))
require(ggplot2)
ggplot(data=test, aes(x=v)) +
geom_histogram() +
coord_flip() +
facet_grid(. ~ g)
Produces this image. In my opinion, the only step missing here to create a population pyramid is to invert the x axis of the first facet, so that is goes from 50 to 0, while keeping the second untouched. Can anyone help?

Here is a solution without the faceting. First, create data frame. I used values from 1 to 20 to ensure that none of values is negative (with population pyramids you don’t get negative counts/ages).
Then combined two
geom_bar()calls separately for each ofgvalues. ForFcounts are calculated as they are but forMcounts are multiplied by -1 to get bar in opposite direction. Thenscale_y_continuous()is used to get pretty values for axis.UPDATE
As argument
subset=.is deprecated in the latestggplot2versions the same result can be atchieved with functionsubset().UPDATE 2
As the dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0 it might be useful to update the 2nd call of `geom_bar` to use `after_stat` instead, so: