将百分比标签添加到堆叠的barplot ggplot

时间:2020-03-02 17:26:30

标签: r ggplot2

如何在此堆积条形图上添加百分比标签,并用相应的百分比标记堆积条形图的每个组成部分?

ggplot(mtcars, aes(cyl, fill = factor(gear))) +
  geom_bar(position = "fill") +
  scale_y_continuous(labels = scales::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')

1 个答案:

答案 0 :(得分:3)

我想说,最简单的方法是做一些数据准备,以获得比例/百分比:

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

一种更简单的方法是使用sjPlot-package

sjPlot::plot_xtab(mtcars$cyl, mtcars$gear, bar.pos = "stack", margin = "row")

reprex package(v0.3.0)于2020-03-02创建