Home > Software engineering >  facet_wrap: omit unneeded x-entries
facet_wrap: omit unneeded x-entries

Time:08-10

I have a plot with facet_wrap where some combinations of my x-axis and the faceting variable are not present in the data set.

I would like to omit these completely in the plot but cannot find a way of doing so.

Consider this example:

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)

This produces the following plot:

plot_output

Note, however, that e.g. auto(l5) has no displ_char values of a_three (likewise for manual(m5) and d_six. I would like to remove those. The desired output looks like this (produced with image editing):

desired_output

This could be achieved by (on-the-fly) data manipulation or plotting options, but only factor levels that are actually present should be plotted on the x-axis.

CodePudding user response:

You need the scales = "free_x" argument in facet_wrap.

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")

Created on 2022-08-09 by the reprex package (v2.0.1)

  • Related