I have a variable that I want to visualise as a stacked bar chart the proportion of the total (in my case, the proportion of students but there are part students) that fall into each group. But I want the total (count of students, but taking into account the part students) as the label for each piece of the bar.
MWE using cars:
library(tidyverse)
testPlot <- mtcars %>%
select(mpg, disp, hp, vs, gear) %>%
mutate(gearFactor = factor(gear))
ggplot(testPlot, aes(x = vs, y = hp, fill = gearFactor)) +
geom_col(position = "fill") +
# geom_text(aes(label = after_stat(y)), stat = "summary", fun = sum,
# size = 3, colour = "white", position=position_fill(vjust=0.5)) +
scale_y_continuous(name = "Share of Power", labels = scales::percent) +
scale_fill_viridis_d(name = "Classification") +
theme_minimal()
This code works fine and produces a stacked bar plot.
The problem is the labels. I want each of the bar sections to have the sum of the variable 'hp'. I have found various posts such as How do you add quantifying "count" labels to bar graphs made with ggplot2 in R? that use geom_text(aes(label = ..count..), stat = "count", position = "fill")
and I know that after_stat()
has replaced the ..STAT..
approach but haven't used it before. The answer at draw the sum value above the stacked bar in ggplot2 is where I got the labelling calculation.
If I uncomment my labelling lines, I get the error
Error: Discrete value supplied to continuous scale
Have tried various edits and just can't make it work. Other attempts have messed up the scaling or other failures. Can someone please tell me what I am doing wrong?