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

问题描述

我有

enter image description here

如您所见,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$response计算p$study,然后对bind_rows计算每个response的所有p$treatment

我有

 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,15中的sstRstudy 2,22,3,4,5,6,7中的SSA

如何在每个facet_wrap中省略这些“空”组,使其仅包含实际上应用了studies的{​​{1}}?

p$treatment

解决方法

也许是这样

#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')

输出:

enter image description here