Pusto
Pusto

Reputation: 65

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?

Upvotes: 0

Views: 326

Answers (2)

Henry
Henry

Reputation: 6784

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,

Scale decided by red curves

which bases the y-axis scale on the y1 curve (though not on your 4 and 8).

Upvotes: 1

Andrie
Andrie

Reputation: 179438

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")

enter image description here

Upvotes: 2

Related Questions