r - R:使用 dplyr 和 geom_text 计算和显示百分比
问题描述
df <- data.frame(Language = factor(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), levels = 1:2, labels = c("GER", "ENG")),
Agegrp = factor(c(1, 2, 3, 1, 2, 4, 1, 2, 3, 2, 3, 3, 3, 3, 1, 1, 2, 1, 1, 4), levels = c( 1, 2, 3, 4), labels = c("10-19", "20-29", "30-39", "40+"))
)
df %>% ggplot(aes(x = Agegrp, fill = Language)) +
geom_bar(position = 'dodge') +
labs(title = "Age-structure between German and English",
y = "Number of persons")
使用上面的示例数据,我可以创建以下图。但
- 如何计算每种语言中每个年龄组的百分比(使用 dplyr)和
- 如何用百分比绘制相同的图(y 轴应该是百分比)?
在这个例子中,百分比很容易看出,因为两种语言都有相同数量的案例 (10),但这不一定是真实数据的情况。谢谢你的帮助!
解决方案
要计算 a 中每个Agegrp
的百分比,Language
您可以尝试 -
library(dplyr)
library(ggplot2)
df %>%
count(Agegrp, Language) %>%
group_by(Language) %>%
mutate(n = prop.table(n)) %>%
ungroup %>%
ggplot(aes(x = Agegrp, y = n, fill = Language)) +
geom_col(position = 'dodge') +
scale_y_continuous(labels = scales::percent) +
labs(title = "Age-structure between German and English",
y = "Percentage of persons")
推荐阅读
- javascript - 基于 Javascript 中的过滤器数组的过滤器数组
- tensorflow - 如何安装支持 gpu 的 Keras?
- python - https://s3.zoneame.amazonaws.com/ 的 SSL 验证失败 [SSL: CERTIFICATE_ VERIFY_FAILED] 证书验证失败 (_ssl.c:749)
- rabbitmq - 激活 RabbitMQ 磁盘或内存警报时 spring-cloud-stream-rabbit-binder 如何工作?
- r - NLP 包中的多米诺效应错误/警告?
- linux - 查找日期命令不接受格式的三个时间戳之间的差异
- groovy - 如何在 REST 调用中省略参数
- php - 没有从数据库中获取下拉元素
- javascript - 图层滑块导航在wordpress中的IOS上不起作用
- c - 从文件中捕获用逗号分隔的带引号的字符串