Drew Steen
Drew Steen

Reputation: 16627

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

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.

Upvotes: 7

Views: 3668

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162461

In your case, either of the following will work:

p + expand_limits(y=0)

p + aes(ymin=0)

Upvotes: 8

Related Questions