# Plotting in Grids

This is post #12 in a running series about plotting in R.

I regularly find myself wanting to show arrays or grids of plots in R. This is straightforward using `par` and `mfrow` as long as you want a symmetric, evenly spaced grid of plots. Unfortunately, this often is not what I want. Even more unfortunately, this is a hard question to google for. I’ve tried array of plots, grid of plots, matrix of plots, asymmetric grids of plots, asymmetric arrays, uneven grids of plots, uneven mfrow, uneven mfcol, etc, and nothing worked. (Searches listed here in the hopes that other people with the same question will find the answer.)

I actually didn’t think this could be accomplished without using lattice and ggplot2, but I recently discovered that it can be done with R’s base plotting functions. The function layout provides what we’re looking for. It takes a matrix describing where you want your sequence of plots to go. After creating your layout, you can use layout.show to visually see where your plots will go. Let’s take a look at some examples.

This creates a two by two grid, exactly as `mfrow` does. For comparison, this creates a 2 by 2 grid as `mfcol` does. The only difference is the order of the plot numbers in the matrix. We can put 0 in any position in the matrix to not plot there. Now, let’s just have one plot use all of the left column. The trick to spanning columns like this is to repeat the number of the plot that you want to span — note that 1 occurs twice in the layout matrix. Finally, we can set widths for the columns (or for the rows — just use heights instead of widths). Now, let’s show off what I originally wanted to do: display a plot of two dimensions of a distribution, along with the marginal distributions. I’m wrapping the functionality up into a function so it’s easy to reuse. I use plot to show the sample and barplot to show the distribution as calculated by hist.

Now that all the prep is done, this shows a multivariate normal distribution with no correlation between the two variables. Note the shape of the marginal distributions. And finally, for contrast, a correlated multivariate normal. 