[英]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-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)由reprex 包(v0.3.0) 于 2020 年 3 月 2 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.