r - ggplot2 组覆盖填充命令
问题描述
我对 R 和学习 ggplot 有点陌生,并面临要修复的代码
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = color, y = after_stat(prop),group=1))
我需要它来显示分组的颜色,但似乎 group 命令覆盖了填充命令。
我应该如何处理?如果可能的话,请参考一个来源我想了解更多关于它的信息
解决方案
有时最好先计算要绘制的数据,以更好地了解 ggplot2 stats 发生的情况(此处after_stat
)
也许你想做这样的事情:
library(ggplot2)
d2 <- diamonds %>%
group_by(cut, color) %>%
summarise(n = n()) %>%
mutate(prop = n / sum(n))
然后计算 prop ,您可以使用它geom_col
来代替geom_bar
:
ggplot(data = d2) +
geom_col(mapping = aes(x = cut, fill = color, y = prop))
然后您可以使用 geom_text 添加标签:
ggplot(data = d2) +
geom_col(mapping = aes(x = cut, fill = color, y = prop)) +
geom_text(mapping = aes(x = cut, group = color, y = prop,
label = scales::percent(prop, accuracy = 1)),
position = position_fill(vjust = 0.5))
要全局计算道具,请取消组合:
library(tidyverse)
d2 <- diamonds %>%
group_by(cut, color) %>%
summarise(n = n()) %>%
ungroup() %>%
mutate(prop = n / sum(n))
ggplot(data = d2) +
geom_col(mapping = aes(x = cut, fill = color, y = prop))
推荐阅读
- python - 如何使用 StringIO() 对象作为程序的标准输入将字符串发送到输入语句,
- angular - 重定向到子路由
- c - SDL_OpenAudioDevice:从实时处理的源缓冲区连续播放
- reactjs - 如何在反应中导出多个类
- asp.net - .NET 核心问题中的清洁/洋葱架构
- r - 如何将闪亮应用程序中的数据写入 excel/csv 文件?正是我想将股票价格的值写入 excel/csv 文件
- c++ - “从 'const char*' 到 'char' [-fpermissive] 错误的无效转换”不会消失 plz
- python - 有没有更快的方法来合并两个文件而不是逐页合并?
- android - 简单的广播接收器是否足以处理 FCM 事件?
- jquery - JQuery / Select2 width = 100% 在加载时创建“闪烁”,如何防止?