[英]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参数更改为position = "dodge"
, 每个观察都会根据Gender进行躲闪,因此条形的高度表示每个年龄组/ Gender组合的最大Impressions值。 您可以将其视为同一年龄段/性别组合中的每个观察形成一个长队列,这样从前面,您只能看到一个观察。
为了绘制按性别排列的值堆栈,您可以首先计算汇总值:
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")
,因此您也可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.