【问题标题】:how do i fill in missing ages in an age pyramid graph?如何在年龄金字塔图中填写缺失的年龄?
【发布时间】:2019-10-25 19:13:45
【问题描述】:

我有一个包含如下年龄和性别信息的 data.frame:

 +-----+--------+
 | age | gender |
 +-----+--------+
 |  48 | male   |
 |  35 | male   |
 |  25 | female |
 |  75 | female |
 |  36 | male   |
 |  49 | female |
 |  21 | male   |
 |  61 | female |
 |  18 | female |
 +-----+--------+

可以使用此代码生成类似的数据框:

data <- data.frame(age=sample(18:80,120,replace=T), gender=c('male','female'))

我想使用 ggplot 在年龄金字塔图中显示这些数据。问题是,并非所有年龄都在我的数据中表示。对于我的概述,重要的是 x 轴具有恒定的刻度大小。我尝试使用 scale_x_discrete 参数,但这并没有填充空行。这是我目前使用的代码:

ggplot(data = data, aes(x = as.factor(age), fill = gender)) +
  geom_bar(data = subset(data, gender == "female")) +
  geom_bar(data = subset(data, gender == "male"), mapping = aes(y = - ..count.. ), position = 
"identity") +
  scale_y_continuous(labels = abs) +
  scale_x_discrete(breaks = seq(18, 80, 1), labels = abs(seq(18,80, 1))) +
  coord_flip()

如您所见,缺少例如 age = 59 的年龄线。有什么方法可以使这个轴均匀分布吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以计算数据中存在的每种组合的数量,然后使用tidyr::complete 添加任何缺失的组合:

    library(tidyverse)
    data.frame(age=sample(18:80,120,replace=T), gender=c('male','female')) %>%
      count(age, gender) %>%
      complete(age = 18:80, gender, fill = list(n=0)) %>%
      mutate(n = if_else(gender == "male", -n, n)) %>%
    
      ggplot(aes(x = age, n, fill = gender)) +
      geom_col() + 
      scale_y_continuous(labels = abs) +
      scale_x_continuous(breaks = 18:80, minor_breaks = NULL, expand = c(0,0)) +
      coord_flip()
    

    (经过思考,一种可能足够的更短的方法是使用连续的 x 标度,以便枚举所有年龄,而不管数据中的外观如何。例如scale_x_continuous(breaks = 18:80, minor_breaks = NULL, expand = c(0,0)) +

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2012-03-26
      相关资源
      最近更新 更多