【问题标题】:facet_wrap: omit unneeded x-entriesfacet_wrap:省略不需要的 x 条目
【发布时间】:2022-08-09 23:50:51
【问题描述】:

我有一个带有 facet_wrap 的图,其中我的 x 轴和 faceting 变量的某些组合不存在于数据集中。

我想在情节中完全省略这些,但找不到这样做的方法。

考虑这个例子:

ggplot(mpg %>% filter(displ>3, trans %in% c(\"auto(l5)\", \"manual(m5)\"), cty<15) %>% mutate(displ=as.integer(displ), displ_char=case_when(displ==3~\"a_three\", displ==4~\"b_four\", displ==5~\"c_five\", displ==6~\"d_six\")), 
   aes(x=displ_char, y=cty)) + geom_boxplot() + facet_wrap(vars(trans), nrow = 1)

这会产生以下图:

但是请注意,例如auto(l5) 没有 displ_chara_three 值(manual(m5)d_six 也是如此。我想删除它们。所需的输出看起来像这样(通过图像编辑产生):

这可以通过(即时)数据操作或绘图选项来实现,但只有实际存在的因子水平才应绘制在 x 轴上。

    标签: ggplot2 facet-grid


    【解决方案1】:

    您需要 facet_wrap 中的 scales = "free_x" 参数。

    library(dplyr)
    library(ggplot2)
    
    ggplot(mpg %>% filter(displ>3, trans %in% c("auto(l5)", "manual(m5)"), cty<15) %>% mutate(displ=as.integer(displ), displ_char=case_when(displ==3~"a_three", displ==4~"b_four", displ==5~"c_five", displ==6~"d_six")), 
           aes(x=displ_char, y=cty)) + geom_boxplot() + facet_wrap(vars(trans), nrow = 1, scales = "free_x")
    

    reprex package (v2.0.1) 于 2022 年 8 月 9 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 2013-03-13
      • 2012-03-29
      • 2017-07-07
      • 2022-12-01
      • 2012-01-10
      • 1970-01-01
      相关资源
      最近更新 更多