Search code examples
rggplot2facet

ggplot2 facets with different y axis per facet line: how to get the "best" from both facet_grid and facet_wrap?


Context: I have a dataframe with a numeric column Type recorded for two categories (conc and uptake in the example below). With my real data, I need to make a facetted plot as presented below.

Problem: Setting scales = "free_y" does not "free" the y scale for facets of the same line, indeed, when values of the category conc are much bigger than the values of the category uptake, the latter is "crushed".

Question: is it possible to free the y axis scale for facets of the same line using facet_grid() or change facet-label from facet_wrap() to match those of facet_grid()?

Trials and errors: I have tried facet_wrap() but I did not acheived the neat layout of facet_grid() while the y-axis scale was good. Maybe there is a way to define facet_wrap() facet-labels but playing around with switch (i.e. strip_position) arguments has not been a success.

I am aware that some SO post are already looking for something similar (see How to position strip labels in facet_wrap like in facet_grid) but maybe (I hope ^^) another, maybe "easier" solution came out since.

library(magrittr) # for %>%
library(tidyr) # for pivot longer
library(ggplot2)
df <- CO2 %>% pivot_longer(cols = c("conc", "uptake"))
# nice facet labels but bad y-axis
ggplot(data = df, aes(x = Type, y = value)) +
  geom_boxplot() +
  facet_grid(Treatment ~ name, scales = "free_y")

# nice y-axis but bad facet labels
ggplot(data = df, aes(x = Type, y = value)) +
  geom_boxplot() +
  facet_wrap(Treatment ~ name, scales = "free_y")

Created on 2022-03-30 by the reprex package (v2.0.1)


Solution

  • The ggh4x::facet_grid2() function has an independent argument that you can use to have free scales within rows and columns too. Disclaimer: I'm the author of ggh4x.

    library(magrittr) # for %>%
    library(tidyr) # for pivot longer
    library(ggplot2)
    
    df <- CO2 %>% pivot_longer(cols = c("conc", "uptake"))
    
    ggplot(data = df, aes(x = Type, y = value)) +
      geom_boxplot() +
      ggh4x::facet_grid2(Treatment ~ name, scales = "free_y", independent = "y")
    

    Created on 2022-03-30 by the reprex package (v2.0.1)