首页 > 解决方案 > ggplot2 组覆盖填充命令

问题描述

我对 R 和学习 ggplot 有点陌生,并面临要修复的代码

ggplot(data = diamonds) +
  geom_bar(mapping = aes(x = cut, fill = color, y = after_stat(prop),group=1))

我需要它来显示分组的颜色,但似乎 group 命令覆盖了填充命令。

我应该如何处理?如果可能的话,请参考一个来源我想了解更多关于它的信息

标签: rggplot2

解决方案


有时最好先计算要绘制的数据,以更好地了解 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))


推荐阅读