Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create part-fixed, part-free axis limits on facets with ggplot?

Tags:

r

ggplot2

I'd like to create a faceted plot using ggplot2 in which the minimum limit of the y axis will be fixed (say at 0) and the maximum limit will be determined by the data in the facet (as it is when scales="free_y". I was hoping that something like the following would work, but no such luck:

library(plyr)
library(ggplot2)

#Create the underlying data
l <- gl(2, 10, 20, labels=letters[1:2])
x <- rep(1:10, 2)
y <- c(runif(10), runif(10)*100)
df <- data.frame(l=l, x=x, y=y)

#Create a separate data frame to define axis limits
dfLim <- ddply(df, .(l), function(y) max(y$y))
names(dfLim)[2] <- "yMax"
dfLim$yMin <- 0

#Create a plot that works, but has totally free scales
p <- ggplot(df, aes(x=x, y=y)) + geom_point() + facet_wrap(~l, scales="free_y") 
#Add y limits defined by the limits dataframe
p + ylim(dfLim$yMin, dfLim$yMax)

It's not too surprising to me that this throws an error (length(lims) == 2 is not TRUE) but I can't think of a strategy to get started on this problem.

like image 904
Drew Steen Avatar asked Oct 04 '12 16:10

Drew Steen


1 Answers

In your case, either of the following will work:

p + expand_limits(y=0)

p + aes(ymin=0)
like image 127
Josh O'Brien Avatar answered Nov 01 '22 06:11

Josh O'Brien