1

I want to create population pyramid. in mydata, I have two groups of data for two countries italy and india . what I need is creating population pyramid for both country.

df<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "male", 
population =c(180,160,130,140,150,160,170,90,85,80,75,70,65,60,40), country = "italy")
                
df1<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "female", 
population =c(160,150,120,130,140,150,160,80,75,70,65,60,55,50,30),country  = "italy")

df2<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "male", 
 population =c(185,165,135,148,159,166,177,99,89,88,74,73,68,63,43), country = "india")

df3<- data_frame(age= c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70), gender = "female", 
 population =c(150,143,117,126,134,144,157,77,71,67,56,51,49,40,24), country = "india")
mydata<- rbind(df,df1,df2,df3)
mehmo
  • 409
  • 2
  • 8
  • Maybe you should start with https://stackoverflow.com/questions/14680075/simpler-population-pyramid-in-ggplot2 or https://stackoverflow.com/questions/31897329/population-pyramid-plot-with-ggplot2-and-dplyr-instead-of-plyr – stefan Jun 22 '21 at 11:59
  • I saw that post but did not help me. – mehmo Jun 22 '21 at 12:07

1 Answers1

2

Maybe this is what you are looking for:

library(ggplot2)

ggplot(data=mydata, aes(x=age, y = ifelse(gender == "male", - population, population), fill=gender)) + 
  geom_col() + 
  facet_wrap(~country) +
  coord_flip()

stefan
  • 90,330
  • 6
  • 25
  • 51
  • @ thanks stefan. can I animate this two pyramids? – mehmo Jun 22 '21 at 12:20
  • In principle this is possible using `gganimate`. See e.g. https://towardsdatascience.com/population-pyramid-animation-cfa7c1a79a63 – stefan Jun 22 '21 at 12:25