R – Align multiple ggplot2 plots with grid

data-visualizationggplot2r

Context

I want to plot two ggplot2 on the same page with the same legend. http://code.google.com/p/gridextra/wiki/arrangeGrob discribes, how to do this. This already looks good. But… In my example I have two plots with the same x-axis and different y-axis. When the range of the the y-axis is at least 10 times higher than of the other plot (e.g. 10000 instead of 1000), ggplot2 (or grid?) does not align the plots correct (see Output below).

Question

How do I also align the left side of the plot, using two different y-axis?

Example Code

x = c(1, 2)
y = c(10, 1000)
data1 = data.frame(x,y)
p1 <- ggplot(data1) + aes(x=x, y=y, colour=x) + geom_line()

y = c(10, 10000)
data2 = data.frame(x,y)
p2 <- ggplot(data2) + aes(x=x, y=y, colour=x) + geom_line()


# Source: http://code.google.com/p/gridextra/wiki/arrangeGrob
leg <- ggplotGrob(p1 + opts(keep="legend_box"))
legend=gTree(children=gList(leg), cl="legendGrob")
widthDetails.legendGrob <- function(x) unit(3, "cm")
grid.arrange(
  p1 + opts(legend.position="none"),
  p2 + opts(legend.position="none"),
  legend=legend, main ="", left = "")

Output

Example image

Best Answer

A cleaner way of doing the same thing but in a more generic way is by using the formatter arg:

p1 <- ggplot(data1) +
    aes(x=x, y=y, colour=x) +
    geom_line() + 
    scale_y_continuous(formatter = function(x) format(x, width = 5))

Do the same for your second plot and make sure to set the width >= the widest number you expect across both plots.

Related Topic