1
votes

In facet_grid, ggplot2 automatically defines the range of values that will be displayed on the Y-axis. If using scale = "free_y", the range of values might differ across facets.

Alternatively the user can define himself/herself the range of values that will be displayed on the Y-axis using scale_y_continuous. But in that case, the ranges will be the same for all facets.

My question is: Is there a way for the user to define facet-specific Y-axis ranges?

Example: Let's assume that the facet variable takes 2 values (A and B) and the Y values range between 0 and 10 for A and between 20 and 100 for B. Is there a way to instruct ggplot2 to display only Y values between 0 and 5 for A and between 20 and 50 for B? Or, more complicated, to instruct ggplot2 to display all Y values for A (default) but only between 20 and 50 for B?

With lattice, defining panel specific Y-axis ranges is possible using a pre-panel. I was wondering if this is possible with ggplot2?

PS: I am of course not interested to select Y vales to be displayed before running the plot, but only at the time of display.

1

1 Answers

2
votes

I don't know of a way to tell ggplot2 to do this itself, but it isn't terribly hard to achieve the same effect yourself simply by subsetting your data:

#Sample data matching your description
dat <- data.frame(x = runif(100),
                  y = c(runif(50,0,10),runif(50,20,100)),
                  grp = rep(LETTERS[1:2],each = 50))

#Plotting everything                      
ggplot(dat) + 
    facet_wrap(~grp,scales = "free_y") + 
    geom_point(aes(x = x,y = y))

#Plotting only 0-5 in grp A, 20-50 in grp B     
ggplot(subset(dat,(grp == 'A' & y <= 5) | (grp == 'B' & y >= 20 & y <= 50))) + 
    facet_wrap(~grp,scales = "free_y") + 
    geom_point(aes(x = x,y = y))