【问题标题】:add percentage labels to stacked barplot ggplot将百分比标签添加到堆叠条形图 ggplot
【发布时间】:2020-03-02 17:26:30
【问题描述】:

如何向此堆叠条形图添加百分比标签,堆叠条的每个组件都标有相应的百分比?

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

【问题讨论】:

标签: r ggplot2


【解决方案1】:

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

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 年 3 月 2 日创建

【讨论】:

  • 是否有避免使用数据准备/创建新的df?实际用例要求它更通用。此外,不幸的是,由于我公司的防火墙,我无法访问 sjPlot。只批准常见的软件包。
  • 我不知道任何避免计算比例的解决方案,因为至少您需要知道标签的正确位置。但是这几个月我没有详细关注ggplot2-development,也许是有可能的。
  • 好的,一个不修改数据的解决方案:rstudio-pubs-static.s3.amazonaws.com/…
猜你喜欢
  • 2017-11-27
  • 2018-06-04
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多