开发者

Date labels overlap when putting multiple ggplot plots on single page

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


either rotate the axis labels

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

Note that opts is deprecated in current versions of ggplot2. This functionality has been moved to theme():

+ theme(axis.text.x = element_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).


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜