【发布时间】:2019-03-02 04:30:27
【问题描述】:
如何将每个类别的百分比添加到轴的堆积条形图中,而不是填充。例如,我有以下数据集:
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"))
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)*100))
dat$proportionR <- round(dat$proportion, digits =0)
dat<-dat %>%
group_by(age_group) %>%
mutate(age_per = sum(value)) %>%
ungroup() %>%
mutate(age_per = round((age_per/sum(value))*100))
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)
我想要的是一种自动方式,可以从 y 轴为每个组添加 总百分比,同时忽略每个组内的百分比。我的工作流程确定了正确的百分比,但将其复制到堆栈中的每个子组。我希望geom_text 在栏结束后立即放置在空白处。
请注意,该问题与以下 SO Q -Adding percentage labels to a bar chart in ggplot2 并非重复,因为此问题涉及每个条形图内有堆叠组时的百分比(前者仅用于条形图)。
另外,强调自动化。我可以执行以下操作,但在我的真实数据集中,我有更多的年龄组间隔,这使得下面的方法站不住脚。
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(y= 5.2, x=1, label = "33%"), color = "#740404", size =5) +
geom_text(aes(y= 3.2, x=2, label = "20%"), color = "#740404", size =5) +
geom_text(aes(y= 7.2, x=3, label = "47%"), color = "#740404", size =5)
【问题讨论】:
-
我有点困惑,你要添加的具体数字是多少?
-
@PoGibas 我只想要一个数字,该数字应与您当前在第一张图表中看到的重复数字相同。百分比计算为每个年龄组(不考虑性别)的总数除以数据集中值的总数。请参阅上面的补充内容。