首页 > 解决方案 > 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调用类似地定位在理想的相关柱上。任何指导将不胜感激。

标签: rggplot2dplyrgeom-bar

解决方案


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)

enter image description here


推荐阅读