[英]add percentage labels to stacked barplot ggplot
如何向此堆疊條形圖添加百分比標簽,堆疊條形的每個組件都標有相應的百分比?
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')
我想說最簡單的方法是做一些數據准備,以獲得比例/百分比:
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 包(v0.3.0) 於 2020 年 3 月 2 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.