In ggplot I want to create a facet grid where the y axes are free. This scales option is available in facet_wrap() but I want to keep the grid layout. I have attached a drawn example of what I want.

EDIT: I added some code for calrity
# Create data
nX <- 3
nY <- 3
nVal <- 2
df <- data.frame(M = sort(rep(paste0("M",1:nX), nVal * nY)),
n = rep(sort(paste0("n",rep((1:nY)-1, nVal))),nX),
G = rep(1:2,nX * nY),
val = c(100,300,20,10,1,2,10,25,NA,NA,0.1,0.2,25,27,2,5,0.5,0.6))
# Delete observations to resemble my data
df <- subset(df, !is.na(val))
# scales does not work in facet_grid(), thus obscuring trends for low values
ggplot(df, aes(x = G,
y = val)) +
geom_line()+
ylim(0,NA)+
facet_grid(n ~ M,scales = "free_y")

Note that no trends are visible for low values because in the grid they are obscured by the high values.
# the grid is lost in facet_wrap()
ggplot(df, aes(x = G,
y = val)) +
geom_line()+
ylim(0,NA)+
facet_wrap(n+M~.,scales = "free_y")

Note that the grid layout is lost.
The dev/github version of ggh4x has facet_grid2() which allows these independent axes within a grid layout. (Disclaimer: I'm the author of ggh4x.) If you find any bugs or unclear documentation, feel free to leave an issue on the github since I don't think this has been field-tested a lot.
library(ggplot2)
library(ggh4x) # devtools::install_github("teunbrand/ggh4x")
# Create data
nX <- 3
nY <- 3
nVal <- 2
df <- data.frame(M = sort(rep(paste0("M",1:nX), nVal * nY)),
n = rep(sort(paste0("n",rep((1:nY)-1, nVal))),nX),
G = rep(1:2,nX * nY),
val = c(100,300,20,10,1,2,10,25,NA,NA,0.1,0.2,25,27,2,5,0.5,0.6))
# Delete observations to resemble my data
df <- subset(df, !is.na(val))
# scales does not work in facet_grid(), thus obscuring trends for low values
ggplot(df, aes(x = G,
y = val)) +
geom_line()+
ylim(0,NA)+
facet_grid2(n ~ M,scales = "free_y", independent = "y")

Created on 2021-06-09 by the reprex package (v1.0.0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With