我想绘制以下数据:
df <- structure(list(age.cat = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L), levels = c("0-5", "5-10", "10-15", "15-20", "20-25",
"25-30", "30-35", "35-40", "40-45", "45-50", "50-55", "55-60",
"60+"), class = "factor"), sex = c("0", "0", "0", "0", "0", "0",
"1", "1", "1", "1", "1", "1", "0", "0", "0", "0", "0", "0", "1",
"1", "1", "1", "1", "1"), activity_group = c("Food Process",
"Household", "Labor", "Manufacture", "Other", "Resource Acq",
"Food Process", "Household", "Labor", "Manufacture", "Other",
"Resource Acq", "Food Process", "Household", "Labor", "Manufacture",
"Other", "Resource Acq", "Food Process", "Household", "Labor",
"Manufacture", "Other", "Resource Acq"), count = c(97L, 86L,
12L, 75L, 0L, 68L, 62L, 115L, 15L, 88L, 0L, 68L, 153L, 70L, 2L,
71L, 0L, 290L, 175L, 150L, 44L, 138L, 0L, 500L), total = c(146L,
2586L, 34L, 81L, 2767L, 92L, 100L, 2462L, 27L, 95L, 2549L, 121L,
240L, 2002L, 48L, 116L, 1573L, 362L, 256L, 2450L, 75L, 170L,
2180L, 836L), prop = c(0.0169996494917631, 0.0150718541885734,
0.00210304942166141, 0.0131440588853838, 0, 0.0119172800560813,
0.0115801270078446, 0.0214792678371311, 0.00280164363093015,
0.0164363093014569, 0, 0.0127007844602167, 0.0352453351762267,
0.0161253167472932, 0.00046072333563695, 0.0163556784151117,
0, 0.0668048836673577, 0.0293279705044411, 0.0251382604323781,
0.0073738897268309, 0.0231271995977878, 0, 0.0837942014412603
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-24L), groups = structure(list(age.cat = structure(c(1L, 1L,
2L, 2L), levels = c("0-5", "5-10", "10-15", "15-20", "20-25",
"25-30", "30-35", "35-40", "40-45", "45-50", "50-55", "55-60",
"60+"), class = "factor"), sex = c("0", "1", "0", "1"), .rows = structure(list(
1:6, 7:12, 13:18, 19:24), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -4L), .drop = TRUE))
head(df)
# A tibble: 6 × 6
# Groups: age.cat, sex [1]
age.cat sex activity_group count total prop
<fct> <chr> <chr> <int> <int> <dbl>
1 0-5 0 Food Process 97 146 0.0170
2 0-5 0 Household 86 2586 0.0151
3 0-5 0 Labor 12 34 0.00210
4 0-5 0 Manufacture 75 81 0.0131
5 0-5 0 Other 0 2767 0
6 0-5 0 Resource Acq 68 92 0.0119
prop
我想使用(在 y 轴上)相对于age.cat
(在 x 轴上)绘制条形图ggplot2
。但我不知道如何按sex
和进行分组activity_group
。首先,我想在“dodge”位置进行分组sex
,我使用以下代码完成了这一操作:
# Plot
prop %>%
ggplot(aes(age.cat, prop, fill = sex)) +
geom_col(position = "dodge")
但我也希望每个条形都向我显示prop
for activity_group
in 位置“堆栈”。任何帮助表示赞赏,谢谢!
ggplot 中没有组合的闪避和堆叠位置选项。实现闪避堆叠外观的两种方法是:
第一个选项是最简单的:
这是完整性的第二个选项:
还可以使用两个过滤
geom_col
调用并将它们调整到中断的每一侧(这里使用 alpha ,这sex
不是很简洁):