Reputation: 403
How can I add percentage labels to this stacked barplot, with each component of the stacked bars labeled with it's corresponding percentage?
ggplot(mtcars, aes(cyl, fill = factor(gear))) +
geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent)
Edit: Was able to add counts, but still am unable to convert this to percent
ggplot(mtcars, aes(cyl, fill = factor(gear))) +
geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent)+
geom_text(aes(label=stat(count)), stat='count', position='fill')
Upvotes: 0
Views: 1849
Reputation: 7832
I would say the easiest way is to do some data preparation, to get the proportions / percentages:
library(ggplot2)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
data(mtcars)
dat <- as.data.frame(prop.table(table(mtcars$cyl, mtcars$gear), margin = 1))
colnames(dat) <- c("cyl", "gear", "percent")
dat <- dat %>%
group_by(cyl) %>%
mutate(cyl_label_y = 1 - (cumsum(percent) - 0.5 * percent)) %>%
ungroup()
ggplot(dat, aes(cyl, y = percent, fill = factor(gear))) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = scales::percent) +
geom_text(aes(y = cyl_label_y, label = round(100 * percent, 2)))
An even simpler way is to use the sjPlot-package:
sjPlot::plot_xtab(mtcars$cyl, mtcars$gear, bar.pos = "stack", margin = "row")
Created on 2020-03-02 by the reprex package (v0.3.0)
Upvotes: 3