创建具有混合和堆叠条形图的条形图

问题描述

我有一个数据框,其中包含不同年龄段的数据以及土著和非土著人口的计数。我想创建一个复合条形图,用一个代表人口状况(土著或非土著)的条形图,而性别也堆叠在每个条形图上。

我设法分别创建了条形图,但是不确定如何将它们放在一起。

age_group gender status           count
 <chr>     <chr>  <chr>            <dbl>
  0-4       Male   Indigenous       37768
  0-4       Female Indigenous       35496
  0-4       Both   Indigenous       73265
  0-4       Male   Non Indigenous  673289
  0-4       Female Non Indigenous  638089
  0-4       Both   Non Indigenous 1311383


aus_age_cat_counts %>%
  filter(gender %in% c("Male","Female")) %>%
  ggplot(aes(x = age_group,y = count,fill = gender)) +
  geom_col(position="fill")

解决方法

如果您不使用position="fill",则应该同时拥有所需的两种信息(状态计数和每个类别中的性别分布)。您是否正在寻找类似的东西?

# load functions
"%>%" <- magrittr::"%>%"
# set seed and create fake data
seed(1312)
n <- 5000
d <- dplyr::tibble(AGE_GRP=sample(seq(1,100,10),size=n,replace=T,prob=dbinom(1:10,10,0.5)),GENDER=sample(c("Male","Female"),prob=c(.45,.55)),STATUS=sample(c("I","Non-I"),prob=c(.6,.4)))

# plot data
d %>%
  dplyr::count(AGE_GRP,GENDER,STATUS,name="N") %>%
  ggplot2::ggplot(ggplot2::aes(x=STATUS,y=N,fill=GENDER)) +
  ggplot2::geom_col() + 
  ggplot2::theme_minimal()

enter image description here