Population pyramid plot with ggplot2 and dplyr (instead of plyr)

后端 未结 3 1095
小蘑菇
小蘑菇 2020-12-11 23:14

I am trying to reproduce the simple population pyramid from the post Simpler population pyramid in ggplot2

using ggplot2 and dplyr (instead

3条回答
  •  自闭症患者
    2020-12-11 23:31

    You can avoid both dplyr and plyr when making population pyramids with recent versions of ggplot2.

    If you have counts of the sizes of age-sex groups then use the answer here

    If your data is at the individual level (as yours is) then use the following:

    set.seed(321)
    test <- data.frame(v=sample(1:20,1000,replace=T), g=c('M','F'))
    head(test)
    #    v g
    # 1 20 M
    # 2 19 F
    # 3  5 M
    # 4  6 F
    # 5  8 M
    # 6  7 F
    
    library("ggplot2")
    ggplot(data = test, aes(x = as.factor(v), fill = g)) + 
      geom_bar(data = subset(test, g == "F")) + 
      geom_bar(data = subset(test, g == "M"), 
               mapping = aes(y = - ..count.. ),
               position = "identity") +
      scale_y_continuous(labels = abs) +
      coord_flip()
    

提交回复
热议问题