首页 > 解决方案 > 将用于堆叠条形图 ggplot 的数据转换为可用于堆叠百分比图的数据的工作流程

问题描述

我有以下数据集:

(df<-structure(list(age_group = structure(c(3L, 3L, 5L, 3L, 5L, 5L, 
5L, 3L, 5L, 5L, 4L, 4L, 4L, 3L, 5L), .Label = c("65+", "55-64", 
"45-54", "35-44", "25-34", "18-24"), class = "factor"), Gender = c("F", 
"M", "M", "M", "F", "M", "M", "M", "F", "M", "M", "F", "M", "F", 
"M")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-15L), .Names = c("age_group", "Gender")))
    # A tibble: 15 x 2
   age_group Gender
   <fct>     <chr> 
 1 45-54     F     
 2 45-54     M     
 3 25-34     M     
 4 45-54     M     
 5 25-34     F     
 6 25-34     M     
 7 25-34     M     
 8 45-54     M     
 9 25-34     F     
10 25-34     M     
11 35-44     M     
12 35-44     F     
13 35-44     M     
14 45-54     F     
15 25-34     M 

由此,我使用 ggplot 创建了以下堆叠条形图:

在此处输入图像描述

我现在想制作一个堆积百分比图,如下面的 SO 问题所示:创建堆积条形图,其中每个堆栈被缩放为总和为 100%

准备数据以生成堆叠百分比图的工作流程是什么?在我上面发布的 SO 问题中,数据有一个额外的值字段,我没有。

标签: rggplot2

解决方案


dat = aggregate(list(value = 1:NROW(df)), df[c("age_group", "Gender")], length)
dat$proportion = ave(dat$value, dat$age_group, FUN = function(x) x/sum(x))
ggplot(dat, aes(x = age_group, y = proportion, fill = Gender)) +
    geom_col() +
    coord_flip()

推荐阅读