Search code examples
rggplot2ggpubr

How to change the number of rows or panels of a multi panel after using facet.by in ggfunc, ggboxplot


I have the following code. Because variable TEST has three categories I am getting three panel plots (2x2 grid with last panel empty). I would like to have all three panels in a single row. Could please help me how can I do that? Appreciate your help. Thank you

plot <- df1 %>% filter(PKCYC=="Cycle") %>%
  mutate(DOSE=factor(DOSE)) %>%
  group_by(COUNTRY, TEST) %>%
  ggsummarystats(x = "COUNTRY", y = "value", 
  ggfunc = ggboxplot, add = c("jitter"), 
  color = "COUNTRY", palette = "npg",
  facet.by = c("TEST"), xlab=FALSE, ylab="value",   
  legend="none", 
  free.panels = TRUE,
  ggtheme = theme_bw()) 

Solution

  • The issue is that you have set free.panels=TRUE. Not sure what you intended with that (perhaps you want free scales per facet?). But if you want your panels in one row then simply drop it.

    Using a minimal reproducible example based on mtcars:

    library(ggpubr)
    
    df <- mtcars
    df$am <- factor(df$am)
    
    ggsummarystats(
      df,
      x = "am", y = "mpg",
      ggfunc = ggboxplot, add = "jitter",
      color = "am", palette = "npg",
      facet.by = "cyl",
      labeller = "label_both",
      legend = "none",
      xlab = FALSE,
      ylab = "value"
    )
    

    And in case that you want free scales for the facets you could do so by setting scales="free":

    ggsummarystats(
      df,
      x = "am", y = "mpg",
      ggfunc = ggboxplot, add = "jitter",
      color = "am", palette = "npg",
      facet.by = "cyl",
      labeller = "label_both",
      legend = "none",
      xlab = FALSE,
      ylab = "value",
      scales = "free"
    )
    

    Finally, for comparison and to reproduce your issue here is the plot with free.panels=TRUE:

    ggsummarystats(
      df,
      x = "am", y = "mpg",
      ggfunc = ggboxplot, add = "jitter",
      color = "am", palette = "npg",
      facet.by = "cyl",
      labeller = "label_both",
      legend = "none",
      xlab = FALSE,
      ylab = "value",
      free.panels = TRUE
    )