How to ignore one factor when determining ylim with faceted plot
In the following (nonsensical) example, I would like to plot both y1 and y2 curves, but have the ylim determined according to the y1 curve, ignoring y2.
Here's the example:
library(ggplot2)
curves <- data.frame(expand.grid(seq(-2,2,0.1), c(2,4), c(1,2)))
names(curves) <- 开发者_如何学运维c("x","p","c")
curves$y1 <- splat(function(x,p,c, ...) c * p * exp(- x^p))(curves)
curves$y2 <- splat(function(x,p,c, ...) c + x * p)(curves)
curves <- melt.data.frame(curves, id.vars=1:3)
ggplot(curves, aes(x, value, color = variable)) +
geom_line() +
facet_grid(p ~ c, scales="free_y")
I would like the first row to have ylim(0,4) and the second row to have ylim(0,8). Any thoughts? Preferably on how to have ggplot determine the correct limits, rather than entering them manually?
The following works, although it feels clumsy. No doubt you can improve on this.
My workaround is to delete values from the data.frame that you don't want to include in the plot:
curves <- subset(curves, !(curves$p==2 & (curves$value>4 | curves$value<0)))
curves <- subset(curves, !(curves$p==4 & (curves$value>8 | curves$value<0)))
ggplot(curves, aes(x, value, color = variable)) +
geom_line() +
facet_grid(p ~ c, scales="free_y")
If you end with this rather verbose code
ylimits <- c( floor(min(curves$value[curves$variable == "y1"])),
ceiling(max(curves$value[curves$variable == "y1"])) )
ggplot(curves, aes(x, value, color = variable)) +
geom_line() +
facet_grid(p ~ c, scales = "free_y") +
scale_y_continuous(breaks = ylimits[1]:ylimits[2]) +
coord_cartesian(ylim = ylimits)
you get this,
which bases the y-axis scale on the y1 curve (though not on your 4 and 8).
精彩评论