Some sample data:
dfr <- data.frame(
x = rep.int(1:10, 2),
y = runif(20),
g = factor(rep(letters[1:2], each = 10))
)
A simple scatterplot with two facets:
p <- ggplot(dfr, aes(x, y)) +
geom_point() +
facet_wrap(~ g, scales = "free_y")
I can set the axis limits for all panels with
p + scale_y_continuous(limits = c(0.2, 0.8))
(or a wrapper for this like ylim
)
but how do I set different axis limits for different facets?
The latticey way to do it would be to pass a list to this argument, e.g.,
p + scale_y_continuous(limits = list(c(0.2, 0.8), c(0, 0.5)))
Unfortunately that just throws an error in the ggplot2 case.
EDIT:
Here's a partial hack. If you want to extend the range of the scales then you can add columns to your dataset specifying the limits, then draw them with geom_blank
.
Modified dataset:
dfr <- data.frame(
x = rep.int(1:10, 2),
y = runif(20),
g = factor(rep(letters[1:2], each = 10)),
ymin = rep(c(-0.6, 0.3), each = 10),
ymax = rep(c(1.8, 0.5), each = 10)
)
Updated plot:
p + geom_blank(aes(y = ymin)) + geom_blank(aes(y = ymax))
Now the scales are different and the left hand one is correct. Unfortunately, the right hand scale doesn't contract since it needs to make room for the points.
In case it helps, we can now rephrase the question as "is it possible to draw points without the scales being recalculated and without explicitly calling scale_y_continuous
?"
See Question&Answers more detail:
os