This might be the most impossibly stupid question ever, but I'm stumped.
I have two plots in ggplot2, stacked with the gridExtras package. The problem is that I can't get the actual "graph area" within the two plots (not sure the technical name for this) to line up exactly. An illustration:
It's hard to see, but the left edges of the gray-shaded graph areas (i.e. at the axis tick marks) do not match up exactly. For this plot it's not too bad, but when I try to plot a lot more data it gets noticeable because the red vertical lines do not match up.
The code for this looks something like this:
library(ggplot2)
library(gridExtra)
# PLOT 1
# initialize plot
plot1 <- ggplot(xdat, aes(x=time))
+ scale_y_continuous(breaks=seq(0,20,2), label=format2)
+ coord_cartesian(y=c(0,20))
+ xlim(as.POSIXct("07.03.2011 00:00:00", format="%d.%m.%Y %H:%M:%S"), as.POSIXct("08.03.2011 00:00:00", format="%d.%m.%Y %H:%M:%S"))
+ ylab("Level 1")
# add points
plot1 <- plot1 + geom_point(aes(y=units, size=type, shape=type))
+ scale_size_manual(values=c(1,3), guide=FALSE)
+ scale_shape_manual(values=c(16,2), name="Series", labels=c("Continuous", "Manual"))
# connect the points... omitted
# axis labels
plot1 <- plot1 + theme(legend.position="top")
# PLOT 2
plot2 <- ggplot(ydat, aes(x=time))
+ scale_y_continuous(label=format2)
+ coord_cartesian(y=c(0,5_max))
+ xlim(as.POSIXct("07.03.2011 00:00:00", format="%d.%m.%Y %H:%M:%S"), as.POSIXct("08.03.2011 00:00:00", format="%d.%m.%Y %H:%M:%S"))
+ ylab("Level 2")
plot2 <- plot2 + geom_bar(aes(y=units), fill="red", color="red", stat="identity")
# COMBINE
# overlay faint vlines for each ydat... omitted
# make graphs flush when stacking
plot1 <- plot1 + theme(legend.position="top",
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
plot.margin=unit(c(1,1,-0.1,1), "cm"))
plot2 <- plot2 + theme(legend.position="none",
plot.margin=unit(c(-0.5,1,1,1), "cm"))
grid.arrange(plot1,plot2)
It looks to me like the problem is the fact that the y-axis scale for one of the graph is pushing the "graph area" out further to the right than in the other graph. I tried formatting the y-axis scale of the bottom graph to have a trailing white space to match the top graph (e.g. following http://www.cookbook-r.com/Graphs/Axes_(ggplot2)/), but it seems like there should be a more direct way to align the two plot areas.
Does anyone have any insight into this? Such a minor problem, but I have no idea how to navigate the intricacies of ggplot for this.