R: Compute Default 'mfrow' From Number of Plots

n2mfrow {grDevices} | R Documentation

## Compute Default 'mfrow' From Number of Plots

### Description

Easy setup for plotting multiple figures (in a rectangular layout) on one page. This computes a sensible default for `par(mfrow)`.

### Usage

    n2mfrow(nr.plots, asp = 1)

### Arguments

`nr.plots` | integer; the number of plot figures you'll want to draw.
`asp` | positive number; the target aspect ratio (columns / rows) in the output. Was implicitly hardwired to `1`; because of that and back compatibility, there is a somewhat discontinuous behavior when varying `asp` around 1, for `nr.plots <= 12`.

### Value

A length-two integer vector `(nr, nc)` giving the positive number of rows and columns, fulfilling `nr * nc >= nr.plots`, and currently, for `asp = 1`, `nr >= nc >= 1`.

### Note

Conceptually, this is a quadratic integer optimization problem, with inequality constraints nr >= 1, nc >= 1, and nr.plots >= nr*nc (and possibly `nr >= asp*nc`), and two objective functions which would have to be combined via a tuning weight, say w, to, e.g., (nr.plots - nr*nc) + w |nr/nc - asp|.

The current algorithm is simple and not trying to solve one of these optimization problems.

### Author(s)

Martin Maechler; suggestion of `asp` by Michael Chirico.

### See Also

`par`, `layout`.

### Examples

    require(graphics)

    n2mfrow(8) # 3 x 3

    n <- 5 ; x <- seq(-2, 2, len = 51)
    ## suppose now that 'n' is not known {inside function}
    op <- par(mfrow = n2mfrow(n))
    for (j in 1:n)
       plot(x, x^j, main = substitute(x^ exp, list(exp = j)), type = "l",
       col = "blue")

    sapply(1:14, n2mfrow)
    sapply(1:14, n2mfrow, asp=16/9)

[Package grDevices version 4.0.5 Index]