r - r/ggplot:计算组内的条形图份额
问题描述
我ggplot2
用来制作一个按一个变量分组并以份额报告的条形图。
我希望百分比改为分组变量的百分比,而不是整个数据集的百分比。
例如,
library(ggplot2)
library(tidyverse)
ggplot(mtcars, aes(x = as.factor(cyl),
y = (..count..) / sum(..count..),
fill = as.factor(gear))) +
geom_bar(position = position_dodge(preserve = "single")) +
geom_text(aes(label = scales::percent((..count..)/sum(..count..)),
y= ((..count..)/sum(..count..))), stat="count") +
theme(legend.position = "none")
产生这个输出:
我希望百分比(和条形高度)反映“内部cyl
”比例,而不是在整个样本中共享。这可能吗?这会涉及stat
争论吗?
顺便说一句,如果可以将geom_text
调用类似地定位在理想的相关柱上。任何指导将不胜感激。
解决方案
Here is one way :
library(dplyr)
library(ggplot2)
mtcars %>%
count(cyl, gear) %>%
group_by(cyl) %>%
mutate(prop = prop.table(n) * 100) %>%
ggplot() + aes(cyl, prop, fill = factor(gear),
label = paste0(round(prop, 2), '%')) +
geom_col(position = "dodge") +
geom_text(position = position_dodge(width = 2), vjust = -0.5, hjust = 0.5)
推荐阅读
- ios - SwiftUI UIImagePickerController 在横向添加黑条
- angular - 离子角身份验证拦截器不工作
- react-native - 使用 keycloak 的 facebook oauth 错误无法加载 URL:此 URL 的域不包含在应用程序的域中
- uwp - 当我触摸滑块的拇指时会发生什么事件?
- css - 当背景透明时,一侧的弯曲边框仍然在另一侧显示细线,仅在移动设备中 - 为什么会发生这种情况?
- r - 如何模拟抽样分布?
- python - WinError 123 文件名、目录名或卷标语法不正确 --> 导入转换器时
- amazon-web-services - 使用用户池和身份池时的 Lambda 授权方与 IAM 授权方
- ruby-on-rails - 如何在 React Web 应用程序中删除左上角的计时器
- html - 即使表格中没有页脚,我们是否应该在表格中包含表格脚元素?