How do you set different scale limits for different facets?
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
?"
I don't think this is possible yet in ggplot2. This discussion from January suggests the issue is under consideration.
To contract the scale on the left plot remove the points that lie outside the range. E.g. this will reduce the y scale on the right plot to values between 0 and 0.5:
p <- ggplot(dfr, aes(x, y)) +
geom_point(subset=.(g == "a" | (y > 0 & y <.5))) +
geom_blank(aes(y = ymin)) + geom_blank(aes(y = ymax)) +
facet_wrap(~ g, scales = "free_y")
See also my answer to this question.
精彩评论