ggplot:如何从 facet_wrap 中删除空组?

ggplot: how to remove empty groups from a facet_wrap?

我有

如您所见,nystudie 代表的所有研究都打印在 x-axis 上。这会创建很多空组,我需要帮助才能将其删除。

> head(p)
  study response treatment
1    13        1       SSA
2    12        4       SSA
3    10        4       SSA
4     4        4      SSTR
5     4        3      SSTR
6     9        4       SSA

每个 p$study 属于 SSTR SSA。我想每个 p$study 计算 p$response,然后 bind_rows 计算每个 p$treatment.

的所有 response

我有

 p %>%
      mutate(nystudie=as.character(study),
             best.resp =as.factor(response)) %>%    
      bind_rows(., mutate(., nystudie="All")) %>%   
      group_by(nystudie,best.resp) %>%   
      summarise(N=n(),Val=unique(treatment))

这给出了

# A tibble: 6 x 4
# Groups:   nystudie, best.resp [6]
  nystudie best.resp     N Val  
  <chr>    <fct>     <int> <fct>
1 1        3             1 SSTR 
2 1        4             2 SSTR 
3 10       4             1 SSA  
4 11       4             2 SSA  
5 12       3             9 SSA  
6 12       4             4 SSA 

因此,为了对 p$treatmet 进行分层,我写道:

 %>% 
    ggplot(aes(nystudie, N, color = best.resp, fill= best.resp)) +
      geom_col(position = position_dodge2(preserve = "single", padding = 0.1)) +
      facet_wrap(~Val,ncol = 2)

但是,这会创建“空组”。例如。 study 11, 12, 13, 14, 15SSTRstudy 2, 22, 3, 4, 5, 6, 7SSA.

如何在每个 facet_wrap 中省略这些“空”组,所以它只包含 studies 而实际上应用了 p$treatment

p <- structure(list(study = structure(c(12L, 2L, 12L, 12L, 9L, 8L, 
13L, 2L, 12L, 15L, 1L, 13L, 2L, 12L, 9L, 16L, 8L, 3L, 5L, 13L, 
11L, 5L, 4L, 6L, 1L, 9L, 4L, 12L, 1L, 8L, 12L, 11L, 4L, 2L, 6L, 
3L, 12L, 4L, 5L, 8L, 12L, 12L, 5L, 12L, 4L, 13L, 12L, 10L, 4L, 
12L), .Label = c("1", "2", "3", "4", "5", "6", "7", "8", "9", 
"10", "11", "12", "13", "14", "15", "22"), class = "factor"), 
    response = c("3", "3", "3", "4", "3", "1", "4", "3", "3", 
    "4", "4", "4", "3", "3", "2", "4", "1", "3", "3", "4", "4", 
    "2", "3", "3", "3", "2", "4", "3", "4", "1", "4", "4", "3", 
    "3", "4", "3", "3", "3", "2", "1", "4", "4", "3", "3", "4", 
    "4", "3", "4", "4", "3"), treatment = structure(c(2L, 1L, 
    2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 
    1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 
    1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 
    2L, 1L, 2L), .Label = c("SSTR", "SSA"), class = "factor")), row.names = c(NA, 
-50L), class = "data.frame")

也许是这样:

#Code
p %>%
  mutate(nystudie=as.character(study),
         best.resp =as.factor(response)) %>%    
  bind_rows(., mutate(., nystudie="All")) %>%   
  group_by(nystudie,best.resp) %>%   
  summarise(N=n(),Val=unique(treatment)) %>% 
  ggplot(aes(nystudie, N, color = best.resp, fill= best.resp)) +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1)) +
  facet_wrap(~Val,ncol = 2,scales='free')

输出: