考虑使用分组百分比计算进行注释。因为你需要把三个数和六个数相加,
annotate
可以从分组系列中分离。此外,使用适当的性别和年龄组百分比。在另一个下面
base::ave
打电话代替你的
dplyr::group_by
:
agg_df <- aggregate(list(value = 1:NROW(df)), df[c("age_group", "Gender")], length)
dat <- within(agg_df, {
proportion <- ave(value, age_group, FUN = function(x) (x/sum(x)*100))
proportionR <- round(proportion, digits=0)
age_per <- round((ave(value, age_group, Gender, FUN=sum) / sum(value)) * 100)
grp_pct <- round((ave(value, age_group, FUN=sum) / sum(value)) * 100)
})
dat
# age_group Gender value grp_pct age_per proportionR proportion
# 1 45-54 F 2 33 13 40 40.00000
# 2 35-44 F 1 20 7 33 33.33333
# 3 25-34 F 2 47 13 29 28.57143
# 4 45-54 M 3 33 20 60 60.00000
# 5 35-44 M 2 20 13 67 66.66667
# 6 25-34 M 5 47 33 71 71.42857
ggplot(dat, aes(x = age_group, y = value, fill = Gender)) +
geom_col() + coord_flip() + ylab("Visits 2018-2019") +xlab("") +
scale_fill_manual(values= c("#740404", "#AB6868", "#D5B3B3"),
labels = c("Females", "Males", "N/A")) +
theme(legend.title=element_blank()) +
geom_text(aes(label = paste0(age_per, "%")), hjust = 2.7,
position = "stack", color = "white", size =5) +
annotate("text", x=1, y=5.25, label = paste0(dat$grp_pct[[1]], "%")) +
annotate("text", x=2, y=3.25, label = paste0(dat$grp_pct[[2]], "%")) +
annotate("text", x=3, y=7.25, label = paste0(dat$grp_pct[[3]], "%"))
对于动态注释,可能必须使用
ggplot
使用
Reduce
在哪里
+
(实际上不是加号算术运算符)作为
+.gg()
操作人员然后打电话
mapply
反复浏览
unique(grp_pct)
传入x坐标位置并注释标签。剩下的挑战是最佳y坐标未知。
Reduce(ggplot2:::`+.gg`,
c(list(ggplot(dat, aes(x = age_group, y = value, fill = Gender)),
geom_col(), coord_flip(), ylab("Visits 2018-2019"), xlab(""),
scale_fill_manual(values= c("#740404", "#AB6868", "#D5B3B3"),
labels = c("Females", "Males", "N/A")),
theme(legend.title=element_blank()),
geom_text(aes(label = paste0(age_per, "%")), hjust = 2.7,
position = "stack", color = "white", size =5)
),
Map(function(x_loc, g_lab) annotate("text", x=x_loc, y=7.25,
label = paste0(g_lab, "%")),
seq(length(unique(dat$grp_pct))), unique(dat$grp_pct)
)
)
)