How can I add the percent of each category to a stacked bar chart of the axis and not the fill. For example, I have the following dataset:
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)
What I would like is an automated way to add the total percent for each group from the y-axis while disregarding the percentages within each group. My work flow identifies the correct percent but replicates it over each subgroup within the stack. I would like the geom_text
to be placed in the white space right after bar ends.
Just as a note, the question is not a duplicate of the following SO Q -Adding percentage labels to a bar chart in ggplot2 -because this question deals with percents when there are stacked groups within each bar (the former is just for bar plots).
Also, emphasis on automated. I can do the following but in my real data set I have many more age group intervals, which makes the below approach untenable.
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)