-1

I am new to R & ggplot2 and wondering if it is possible to do a population pyramid for Male & Female and comparing each of the gender across two time periods. Please see the screenshot for the details. I have found quite a few resources on this site that show how to build population pyraminds but they all use only one variable i.e. gender. I want to compare gender and time periods in the same chart. Any help is greatly appreciated. Thank you.

Population pyramid

PVS
  • 113
  • 1
  • 1
  • 11
  • 2
    Please make this question *reproducible*. This includes sample code you've attempted (including listing non-base R packages, and any errors/warnings received), and sample *unambiguous* data (e.g., `dput(head(x))` or `data.frame(x=...,y=...)`). Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Sep 19 '20 at 00:04

1 Answers1

2

Here is an idea. First you didn't prepare an example dataset. Therefore I created this df. Note that the Values (number of people) are negative for women.

df <- data.frame(Gender = rep(c("M", "F"), each = 20),
                 Age = rep(c("0-10", "11-20", "21-30", "31-40", "41-50",
                           "51-60", "61-70", "71-80", "81-90", "91-100"), 4),
                 Year = factor(rep(c(2009, 2010, 2009, 2010), each=  10)),
                 Value = sample(seq(50, 100, 5), 40, replace = TRUE)) %>%
  mutate(Value = ifelse(Gender == "F", Value *-1 , Value))

Next step is to everything in a bar plot. The function interaction helps to color the bars by Gender and Year. In scale_fill_manual the color can be specified. Alternativly you can use fill = Gender and alpha = Year if you don't want to use the interaction.

ggplot(df) +
  geom_col(aes(fill = interaction(Gender, Year, sep = "-"), 
               y = Value,
               x = Age), 
           position = "dodge") + 
  scale_y_continuous(labels = abs,
                     expand = c(0, 0)) +
  scale_fill_manual(values = hcl(h = c(15,195,15,195),
                                 c = 100,
                                 l = 65,
                                 alpha=c(0.4,0.4,1,1)),
                    name = "") +
  coord_flip() +
  facet_wrap(.~ Gender, 
             scale = "free_x",
             strip.position = "bottom") +
  theme_minimal() +
  theme(legend.position = "bottom",
        panel.spacing.x = unit(0, "pt"), 
        strip.background = element_rect(colour = "black"))

enter image description here

tamtam
  • 3,541
  • 1
  • 7
  • 21
  • Thank you very much for the solution, greatly appreciated. I will check it with my data. Sorry for not including the sample data. I will make sure to include all the required information from next time. Thank you. – PVS Sep 20 '20 at 01:48