在 ggplot 中使用闪避位置更改列值

Using dodge position in ggplot changing column values

正在尝试创建一个条形图来显示每个性别和年龄组的展示次数。

数据:

> head(ny1)
  Age Gender Impressions Clicks Signed_In age_group   hasimp        ctr  scode
1  36      0           3      0         1   (29,39] (0, Inf] 0.00000000   Imps
2  73      1           3      0         1 (69, Inf] (0, Inf] 0.00000000   Imps
3  30      0           3      0         1   (29,39] (0, Inf] 0.00000000   Imps
4  49      1           3      0         1   (39,49] (0, Inf] 0.00000000   Imps
5  47      1          11      0         1   (39,49] (0, Inf] 0.00000000   Imps
6  47      0          11      1         1   (39,49] (0, Inf] 0.09090909 Clicks


> str(ny1)
'data.frame':   458441 obs. of  9 variables:
 $ Age        : int  36 73 30 49 47 47 0 46 16 52 ...
 $ Gender     : Factor w/ 2 levels "0","1": 1 2 1 2 2 1 1 1 1 1 ...
 $ Impressions: int  3 3 3 3 11 11 7 5 3 4 ...
 $ Clicks     : int  0 0 0 0 0 1 1 0 0 0 ...
 $ Signed_In  : int  1 1 1 1 1 1 0 1 1 1 ...
 $ age_group  : Factor w/ 7 levels "(-Inf,19]","(19,29]",..: 3 7 3 4 4 4 1 4 1 5 ...
 $ hasimp     : Factor w/ 2 levels "(-Inf,0]","(0, Inf]": 2 2 2 2 2 2 2 2 2 2 ...
 $ ctr        : num  0 0 0 0 0 ...
 $ scode      : Factor w/ 3 levels "Clicks","Imps",..: 2 2 2 2 2 1 1 2 2 2 ...

现在这似乎适用于堆叠条形图。

ggplot(data=ny1, aes(x=age_group, y=Impressions)) +
  geom_bar(stat="identity", aes(fill = Gender))

但是,当我简单地添加 position = "dodge" 时,它会改变 y 轴上的分布:

ggplot(data=ny1, aes(x=age_group, y=Impressions)) + 
  geom_bar(stat="identity", aes(fill = Gender), position = "dodge")

为什么第二列衡量的展示次数不同?

您的第一个图是堆叠条形图,其中每个观察值(即数据集的一行)都表示为堆叠的一个薄片。如果查看帮助文件 ?geom_bar,默认参数是 position = "stack".

当您将位置参数更改为 position = "dodge" 时,每个 观察都会根据性别回避,因此条形的高度代表每个年龄段的最大展示次数值组/性别组合。你可以把它看作是同一年龄组/性别组合中的每个观察排成一排长队,这样从前面看,你只能看到一个观察。

为了绘制按性别躲避的值堆栈,您可以先计算汇总值:

library(dplyr)

p <- ggplot(ny %>%
         group_by(age_group, Gender) %>%
         summarise(Impressions_total = sum(Impressions)),
       aes(x = age_group, y = Impressions_total, fill = Gender)) 

p1 <- p + geom_bar(stat = "identity")
p2 <- p + geom_bar(stat = "identity", position = "dodge")

gridExtra::grid.arrange(p1, p2, nrow = 1)
# the bar heights in the two charts match

用于说明的示例数据:

set.seed(123)
ny <- data.frame(
  age_group = sample(c("00-19", "20-29", "30-39"), replace = TRUE, 20),
  Impressions = sample(5:20, replace = TRUE, 20),
  Gender = factor(sample(0:1, replace = TRUE, 20))
)

旁注:geom_col() 等同于 geom_bar(stat = "identity"),因此您也可以使用它。