简体   繁体   中英

add percentage labels to stacked barplot ggplot

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')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM