I want to specify the ylimits of each facet_wrap. Here is a reproducible example:
library(ggplot2)
# Example data
set.seed(123)
df <- data.frame(
x = rep(1:10, 4),
y = c(rnorm(10), rnorm(10, mean = 5), rnorm(10, mean = 10), rnorm(10, mean = 15)),
facet = rep(letters[1:4], each = 10)
)
# Manually specified limits for each facet
facet_limits <- list(
a = c(-2, 2), # Facet a
b = c(2, 8), # Facet b
c = c(8, 12), # Facet c
d = c(12, 18) # Facet d
)
# Plot with manually set facet limits
ggplot(df, aes(x = x, y = y)) +
geom_line() +
facet_grid(. ~ facet, scales = "free_y") +
lapply(seq_along(facet_limits), function(i) coord_cartesian(ylim = facet_limits[[i]]))
How can I achieve this? Thank you!