geom_col with facet_grid with margins=TRUE 没有叠加?

geom_col with facet_grid with margins=TRUE not stacking up?

页边空白处的条形似乎选择了最大的面,而不是像我预期的那样将它们相加。

library(palmerpenguins); library(tidyverse); library(janitor)

penguins_raw %>%
  clean_names() %>%
  ggplot() +
  geom_col(aes(x = clutch_completion, y = body_mass_g, fill = sex), position = "dodge") +
  facet_grid(rows = vars(species), cols = vars(island), margins = TRUE)
#> Warning: Removed 8 rows containing missing values (geom_col).

reprex package (v0.3.0)

于 2020-10-11 创建

编辑 1:这里有一些进一步的调查:如果我只使用 geom_col position = dodge 而没有刻面,我会得到以下结果。 dodge2 向我们展示了它是在彼此之上绘制而不是将它们堆叠起来,所以这就是为什么它看起来像最大值?看起来堆叠的较大闪避条似乎也没有收集闪避 2 中显示的所有数据,但这可能是因为数据是如何分层的?

所以我的问题就变成了:如何同时堆叠和闪避geom_col?

library(palmerpenguins, quietly = TRUE); library(tidyverse, quietly = TRUE); library(janitor, quietly = TRUE)
#> Warning: package 'palmerpenguins' was built under R version 3.6.3
#> Warning: package 'ggplot2' was built under R version 3.6.3
#> Warning: package 'tibble' was built under R version 3.6.3
#> Warning: package 'tidyr' was built under R version 3.6.3
#> Warning: package 'purrr' was built under R version 3.6.3
#> Warning: package 'dplyr' was built under R version 3.6.3
#> Warning: package 'forcats' was built under R version 3.6.3
#> Warning: package 'janitor' was built under R version 3.6.3
#> 
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#> 
#>     chisq.test, fisher.test
penguins_raw %>% clean_names() %>%
  ggplot() + 
  geom_col(aes(x = clutch_completion, y = body_mass_g, col = sex), fill = "grey", position = "dodge") +
  geom_col(aes(x = clutch_completion, y = body_mass_g, fill = sex), position = "dodge2")
#> Warning: Removed 2 rows containing missing values (geom_col).
#> Warning: Removed 2 rows containing missing values (geom_col).

reprex package (v0.3.0)

于 2020-10-11 创建

这个问题可能有一个聪明的解决方案,但也许它可以根据您的需要进行调整?

options(scipen = 100000)
library(palmerpenguins); library(tidyverse); library(janitor)

penguins_raw %>%
  clean_names() %>%
  mutate(clutch_int = factor(str_replace(interaction(clutch_completion,
                                                     sex),
                                         '\.', ' / '),
                             ordered=TRUE)) %>% 
  ggplot() +
  geom_col(aes(x = clutch_int,
               y = body_mass_g,
               fill = sex),
           position = "stack") +
  theme(axis.text.x = element_text(angle = 75, hjust = 1)) +
  facet_grid(scales = "free",
             rows = vars(species), drop = FALSE,
             cols = vars(island), margins = TRUE)