Logical grouping of arbitrary number of plots in R

65 views Asked by At

I have n plots that I want to display in a grid in a single image in R. Using par I can specify beforehand the number of rows and columns to divide the plot. For example, for n = 4, it makes most sense to organize 4 plots in a square 2x2 grid.

par(mfrow=c(2,2))
plot(p1)
plot(p2)
plot(p3)
plot(p4)

I'd like this to work for arbitrary n, however. So, for example, let's say I want to plot 12 plots side by side. It's most practical that the resulting grid of plots be as square-like as possible: so, I'd like a 3x4 grid par(mfrow=c(3, 4)), rather than a 12x1 par(mfrow=c(12, 1)). Or, if I want to plot 11 plots, leaving the 12th grid empty would be fine.

Is there a quick way to do this in R? Otherwise I suppose I have to do some algebra - this is an optimization problem, minimizing the perimeter of the grid given a fixed area n.

2

There are 2 answers

0
baptiste On BEST ANSWER

grDevices::n2mfrow() can do it for you

0
seandavi On

For nplots plots, how about:

rows = floor(sqrt(nplots)) columns = ceiling(sqrt(nplots)) par(mfrow=c(rows,columns))