tags:

views:

70

answers:

2

I am trying to put multiple ggplot2 time series plots on a page using the gridExtra package's arrange() function. Unfortunately, I am finding that the x-axis labels get pushed together; it appears that the plot is putting the same number of x-axis labels as a full-page chart, even though my charts only take up 1/4 of a page. Is there a better way to do this? I would prefer not to have to manually set any points, since I will be dealing with a large number of charts that span different date ranges and have different frequencies.

Here is some example code that replicates the problem.

dfm <- data.frame(index=seq(from=as.Date("2000-01-01"), length.out=100, by="year"), 
    x1=rnorm(100), 
    x2=rnorm(100))
mydata <- melt(dfm, id="index")

pdf("test.pdf")
plot1 <- ggplot(mydata, aes(index, value, color=variable))+geom_line()
plot2 <- ggplot(mydata, aes(index, value, color=variable))+geom_line()
plot3 <- ggplot(mydata, aes(index, value, color=variable))+geom_line()
plot4 <- ggplot(mydata, aes(index, value, color=variable))+geom_line()
arrange(plot1, plot2, plot3, plot4, ncol=2, nrow=2)
dev.off()
A: 

either rotate the axis labels

+opts(axis.text.x=theme_text(angle=45, hjust=1))

or dilute the x-axis

+scale_x_datetime(major = "10 years")

to automatically shift the labels, I think the arrange() function needs to be fiddled with (though I'm not sure how).

apeescape
+1  A: 

I wrote this function to return the proper major axis breaks given that you want some set number of major breaks.

year.range.major <- function(df, column = "index", n = 5){
  range <- diff(range(df[,column]))
  range.num <- as.numeric(range)
  major = max(pretty((range.num/365)/n))

  return(paste(major,"years"))
}

So, instead of always fixing the breaks at 10 years, it'll produce fixed number of breaks at nice intervals.

+scale_x_date(major = year.range.major())

or

+scale_x_date(major = year.range.major(n=3))
JoFrhwld
very nice, I had forgotten about the pretty() function.
apeescape
Thanks for the solution. Unfortunately I am running into a series of errors when I use different date sequences. The year.range.major function itself does not look to have problems, but ggplot blows up. For instance, if I set the date sequence to 100 consecutive days than I get a "number of levels differs" error. If I take the original example and use POSIXlt dates than I get a "cannot allocate vector of length ..." error. And when I redo the original example with consecutive days expressed as POSIXlt objects than I get a "Error in seq.int(r1$year, to$year, by) : 'to' must be finite" error.
Abiel