Date labels overlap when multiple ggplot graphs are placed on the same page

I am trying to put several ggplot2 time series plots on a page using the gridExtra package layout function. Unfortunately, I found that the x-axis labels are shifted together; it seems that the graph puts the same number of x-axis labels in the form of a full-page graph, although my diagrams only occupy 1/4 of the page. Is there a better way to do this? I would prefer that I do not have to manually set any points, since I will deal with a large number of charts that cover different date ranges and have different frequencies.

Here is sample 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()
+3
source share
2

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

, opts ggplot2. theme():

+ theme(axis.text.x = element_text(angle = 45, hjust = 1))

x

+scale_x_datetime(major = "10 years")

, , arr() ( , ).

+5

, , , .

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"))
}

, , 10 , .

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

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

Source: https://habr.com/ru/post/1754513/


All Articles