【问题标题】:age pyramid in R (using group data)R中的年龄金字塔(使用组数据)
【发布时间】:2017-01-26 07:40:44
【问题描述】:

我想在 R 中绘制一个年龄金字塔,类似于 Population pyramid plot with ggplot2 and dplyr (instead of plyr)

问题是我的数据已经按子组聚合。所以我不想计算 65 岁的出现次数,而是所有 65 岁的数字的总和。

例如:

df = structure(list(number = c(26778, 28388, 23491, 18602, 15787, 
24536), gender = c("F", "M", "F", "M", "F", "M"), age = c(65, 
65, 65, 65, 74, 58)), .Names = c("number", "gender", "age"), row.names = c(142L, 
234L, 243L, 252L, 298L, 356L), class = "data.frame")

我应该如何更改此代码:

library("ggplot2")
ggplot(data = df, aes(x = age, fill = gender)) + 
  geom_bar(data = subset(df, gender == "M")) + 
  geom_bar(data = subset(df, gender == "F"), 
           mapping = aes(y = - ..count.. ),
           position = "identity") +
  scale_y_continuous(labels = abs) +
  coord_flip()

【问题讨论】:

    标签: r plot graph charts ggplot2


    【解决方案1】:

    您可以事先汇总数据,然后将其传递给 ggplot,如下所示:

    df1 <- df %>% group_by(gender,age) %>% summarise(s_age = sum(age))
    
    ggplot(data = df1, aes(x = age,y=s_age, fill = gender)) + 
      geom_bar(data = filter(df1, gender == "F"), stat = "identity" ) + 
      geom_bar(data = filter(df1, gender == "M"), stat="identity", aes(y=-s_age) ) + 
      coord_flip() 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多