JonathanTonkin Ecologist

Combining multiple ggplot plots

02 Jun 2015

Note: This was copied from my previous page to get an idea of formatting the Rmarkdown html output to fit here.

This post deals with the simple situation of combining multiple plots in r (made with ggplot2) into a single multiplot. This is a very easy way to align multiple plots, but only looks good if all plot axes align vertically.

Creating the plot in ggplot2

library(ggplot2)
library(grid)
library(gridExtra) 
beetles_plot<-ggplot(beetles_log.mds.df, 
                     aes(MDS1, MDS2, 
                         colour=section, 
                         group=site, 
                         linetype=section)) + 
  geom_point(shape=32, show_guide=F) + 
  theme_bw(base_size=8) + xlab("") + ylab("") +
  geom_path(arrow=arrow(length=unit(3, "mm")), 
            show_guide=F) +
  geom_text(aes(x=MDS1, y=MDS2, label=site), 
            size=3, show_guide=F) +
  labs(title="Beetles") +
  theme(plot.margin=unit(c(0.1,0.5,0.1,0.1), "lines"), 
        panel.background = element_blank(),
        panel.grid.minor = element_blank(),
        panel.grid.major = element_blank(),
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks=element_blank()) +
  scale_colour_manual(values = c("orange1", 
                                 "skyblue1", 
                                 "seagreen4"))

Here's the above plot. Pretend I've done this for four separate plots.

beetles_plot

plot of chunk unnamed-chunk-3

Arranging the four together, using grid.arrange (part of the gridExtra package). ncol is simply specifying how many columns I want. It will work in order from left to right.

grid.arrange(beetles_plot, beetles_plot, beetles_plot, beetles_plot, ncol = 2)

plot of chunk unnamed-chunk-4

The next post will be about how to deal with plots with axes (usually y axes) that don't align due to different scales on the y axis. For example 0-10 vs. 0-100 - the second has an extra value so the y axis will be indented due to less space.