2020-07-26 / Blog 3

Complex panel plots in R

There are many times that two axes are not enough to present all the information you want to convey to the readers. You end up having panel plots with multiple subfigures. Sometimes, these can be so complicated that you need to prepare the figures and merge them separately on Visio, Powerpoint etc. That was what I have been doing for my panel plots for a long time, but then I made the effort and put some time in understanding the layout() in R to eliminate my dependance on any other software to prepare complex panel plots.

First of all, what does layout() function do?

It divides the screen into panels that you can plot an individual figure. That said, let's look at the syntax and the arguments of the function:

layout(matrix, widths,heights)

It requires a matrix defining which plot goes which panel, a vector describing the widths of the columns and a vector describing the heights of the column. Now, let's look at the final plot we want to achieve:

There are 8 subfigures, a legend and some common axes in the figure.The final plot size we want to have is 150 mm x 100 mm. Figures 1a-1d have a width of 70 mm each, and a height of 25 mm. Figures 1e-1h are 35 mm x 35 mm squares. We plot 5-mm gaps on the left and right side of the figures, so we can fit the common axis label there. Same thing is valid for the top and bottom. We will plot the legend on top, and a common axis label in between figures 1a-1d and 1e-1h, as well as below 1e-1h.We use the following line of code to create the layout:

layout(panel,heights=c(5,25,25,5,35,5),

widths=c(5,35,35,35,35,5))


Here the argument panel is a matrix we defined to assign a plot. Panel will be a matrix consisting of 6 rows and 6 columns.

panel <- matrix(NA,6,6)

We first assign the 70-mm wide time series plots (1a-1d) and the 35-mm wide frequency distribution plots (1e-1h) to the cells where we want to have them:

panel[2,2:3] <- c(1,1)

panel[2,4:5] <- c(2,2)

panel[3,2:3] <- c(3,3)

panel[3,4:5] <- c(4,4)

panel[5,2:5] <- c(5,6,7,8)

We then assign the space for legend and common axis labels for the figures:

panel[1,] <- rep(9,6)

panel[4,] <- rep(10,6)

panel[6,] <- rep(11,6)

panel[2:3,1] <- c(12,12)

panel[5,1] <- c(13)

panel[2:3,6] <- c(14,14)

panel[5,6] <- c(15)

Panel matrix looks like the following then, where 1-4 are Figures 1a-1d, 5-8 are Figures 1e-1h,9 will be the legend, 10 and 11 will be the common x-axis labels. 12, 13, 14 and 15 will be used for common y-axis labels. The rest will be plotting each figure in the order of the numbers in the matrix. One of the most crucial things is to use the pty="m" argument in the par() function, so that the full plot area in each subfigure is used.


The scripts used in this post can be found here: Blog Scripts @ Github