为什么在调整group_by函数时图形结果不匹配?

qmelpv7a  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(108)

所以我准备提交一个案例研究,但当我看了数字,我意识到有大量的不一致。
因此,我测试了一些不同的情况,并意识到当我开始向group_by函数中添加更多列名时,列名数量开始急剧减少。
我怀疑它与summary()有关,因为我一直在使用它,但没有完全理解它的用法。
所以我做了一些A/B测试。
我编写了test_1,使其不包含其中一列“time_of_day”

test_1 = annual_2022_v2 %>% 
  group_by(month_of_day, day_of_week, member_casual) %>% 
  summarize(total = sum(ride_length))

我写了

total_month_2022 = test_1 %>% 
  ggplot(aes(factor(day_of_week), total, fill=member_casual)) +
  geom_bar(stat = "identity", position = "dodge") + 
  scale_y_continuous(labels = scales::comma) + facet_wrap(~month_of_day) +
  labs(y= "Time (in mins)", x = "Day") + 
  ggtitle("Total Ride Length Per Month")

它给了我这个

然后我用包含“time_of_day”的原始代码进行了测试

ride_time_2022 = annual_2022_v2 %>% 
  group_by(month_of_day, day_of_week, time_of_day, member_casual) %>% 
  summarize(total = sum(ride_length))

我跑去的地方

total_month_2022 = ride_time_2022 %>% 
  ggplot(aes(factor(day_of_week), total, fill=member_casual)) +
  geom_bar(stat = "identity", position = "dodge") + 
  scale_y_continuous(labels = scales::comma) + facet_wrap(~month_of_day) +
  labs(y= "Time (in mins)", x = "Day") + 
  ggtitle("Total Ride Length Per Month")

它显示了

所以实际的“数据形状”并没有太多的调整,而是缩放,看到它缩小得如此之小是很奇怪的,它与缩放的减少并不一致。
所以我不明白,我不认为在group_by函数中添加一个新元素会对输出有多大的改变,因为我只添加了time_of_day,它允许我查看一天中不同时间段的数据。
也许是因为我没有用正确的方式编码?Summarize()是问题所在吗?
编辑:
我决定检查实际的数据集,数字似乎一致。

例如,一月的偶然事件会互相加起来,所以我很难理解为什么图表显示不同的值。

ubby3x7f

ubby3x7f1#

问题是第二次聚合的数据包含time_of_day的值,也就是说,在ggplot中,每个time_of_day类别都有一个条形图,但是这些条形图没有堆叠(即ggplot2不会对值求和),而是相互叠加,因此比例与第一次代码不同。
以下是基于mtcars的问题的最小可重现示例。
第一个图显示mpg乘以cylgear的总和。

library(ggplot2)
library(dplyr, warn=FALSE)

mtcars2 <- mtcars |>
  mutate(across(c(cyl, gear, am), factor))

mtcars2 |>
  group_by(cyl, gear) |>
  summarise(mpg = sum(mpg)) |>
  ggplot(aes(cyl, mpg, fill = gear)) +
  geom_col(position = "dodge")
#> `summarise()` has grouped output by 'cyl'. You can override using the `.groups`
#> argument.

现在我们添加am作为第三个分组,并使用“相同”的绘图代码,即为了使差异可见,我Map到color aes上,并将填充设置为"transparent"。这里我们看到,对于gear=4,我们现在有两个条形,并且值不相加:

mtcars2 |>
  group_by(cyl, gear, am) |>
  summarise(mpg = sum(mpg)) |>
  ggplot(aes(cyl, mpg, color = gear)) +
  geom_col(position = "dodge", fill = "transparent") +
  geom_text(aes(label = mpg, group = gear), 
            position = position_dodge(width = .9), color = "black")
#> `summarise()` has grouped output by 'cyl', 'gear'. You can override using the
#> `.groups` argument.

解决这个问题的一个方法是使用stat_summary来计算sum

mtcars2 |>
  group_by(cyl, gear, am) |>
  summarise(mpg = sum(mpg)) |>
  ggplot(aes(cyl, mpg, fill = gear)) +
  stat_summary(
    geom = "bar", fun = "sum",
    position = "dodge"
  )
#> `summarise()` has grouped output by 'cyl', 'gear'. You can override using the
#> `.groups` argument.

相关问题