Use mfcol to have plots drawn by column

To plot multiple figures on a single canvas in base R, we can change the graphical parameter mfrow. For instance, the code below tells R that subsequent figures will by drawn in a 2-by-3 array:

par(mfrow = c(2, 3))

If we then run this next block of code, we will get the image below:

set.seed(10)
n <- 50; p <- 3
x <- matrix(runif(n * p), ncol = p)
for (j in 1:p) {
    plot(x[, j], x[, j]^2 + 0.1 * rnorm(n), 
         xlab = paste0("x", j), ylab = paste0("f(x", j, ")^2 + noise"))
    plot(x[, j], x[, j]^3 + 0.1 * rnorm(n),
         xlab = paste0("x", j), ylab = paste0("f(x", j, ")^3 + noise"))
}

Notice how the plots are filled in by row? That is, the first plot goes in the top-left corner, the next plot goes to its right, and so on. What if we want the plots to be filled in by column instead? For instance, in our example above each feature is associated with two panels. It would make more sense for the first column to filled with plots related to x1, and so on.

There is an easy fix for that: instead of specifying the mfrow parameter, specify the mfcol parameter. See the results below:

par(mfcol = c(2, 3))
set.seed(10)
n <- 50; p <- 3
x <- matrix(runif(n * p), ncol = p)
for (j in 1:p) {
    plot(x[, j], x[, j]^2 + 0.1 * rnorm(n), 
         xlab = paste0("x", j), ylab = paste0("f(x", j, ")^2 + noise"))
    plot(x[, j], x[, j]^3 + 0.1 * rnorm(n),
         xlab = paste0("x", j), ylab = paste0("f(x", j, ")^3 + noise"))
}

References:

  1. Graphical layouts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s