ggplot 摘要分组中的奇怪行为

时间:2021-06-14 19:08:33

标签: r ggplot2 dplyr

在对值进行分组时,我的条形图中出现了不合理的数字(geom_col,表示总和)。下图显示了 4 个气缸和 3 个齿轮的汽车的总重量 (wt) 约为 2.5,以及总重量 对于 6 个气缸和 3 个齿轮的汽车,大约为 3.5。前者是合理的,因为summarised的权重是2.46,但后者没有意义,因为summarised的权重是6.68。对于 3 个气缸和 8 个齿轮,它更明显(绘图显示大约 5.5,summarised 重量为 49.2)

mtcars_ex = 
  mtcars %>%
  mutate(cyl = as.character(cyl),
         gear = as.character(gear))

ggplot(data = mtcars_ex,
       aes(y = wt,
           x = gear,
           fill = cyl)) + 
  geom_col(position = "dodge",
           na.rm = TRUE)

enter image description here

mtcars_ex %>% group_by(cyl,gear) %>% summarise(sum(wt))
#`summarise()` has grouped output by 'cyl'. You can override using the `.groups` argument.
# A tibble: 8 x 3
# Groups:   cyl [3]
#  cyl   gear  `sum(wt)`
#  <chr> <chr>     <dbl>
#1 4     3          2.46
#2 4     4         19.0 
#3 4     5          3.65
#4 6     3          6.68
#5 6     4         12.4 
#6 6     5          2.77
#7 8     3         49.2 
#8 8     5          6.74

0 个答案:

没有答案
相关问题