Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align multiple ggplot2 plots with grid

Tags:

People also ask

How do I arrange multiple Ggplots?

To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.

What is ggplotGrob?

ggplotGrob is the same as ggplot_gtable(ggplot_build(x)) ; it's just a convenience function to save some typing. The end goal is to convert the ggplot object, which is essentially a list describing how to build the plot, into a gtable, which is a grid graphical object (grob) that can be drawn on a device.


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