I have 5 plots (let’s call them p_1 through p_5). I want to display them all together in a grid: three of them on the first row, and the two left on the second (and last) row. Naturally, this can be achieved with par(mfrow = c(2, 3)). However, I want the two bottom plots to be centered, so there’s no one-big-space on the bottom-right of the grid. How can this be achieved?
>Solution :
In base R can use layout, which will create a matrix for you to map the figures to:
layout(matrix(c(1,1, # first plot
2,2, # second plot
3,3, # third plot
0, # blank 1/2 space
4,4,# fourth plot
5,5, # 5th plot
0), # blank 1/2 space)
nrow = 2, byrow = TRUE))
plot(1:5, type = "p")
plot(1:5, type = "l")
plot(1:5, type = "b")
boxplot(runif(100))
hist(1:100)
The reason for the doubling of the numbers is because you need to make an even number of "spaces" on the rows – here, each row has 6 "spaces" –
- on the top, you only need three figures for 6 spaces, so each figure takes up two spaces
- on the bottom, you only need two figures for six spaces – each figure takes two spaces, and the remaining two spaces are put on either side to create the correct centering
This allows you to split the "extra" space the bottom and place it on each size (the 0 indicates no plot). It may make more sense to look at it by plot number, so you can see the blank space is "split" to either side:
It may be even easier to visualize if you put two additional plots in there (7 total) to see where they go (and see that each plot in those spaces with only one number is only half the size:
layout(matrix(c(1,1, # first plot
2,2, # second plot
3,3, # third plot
6, # 6th plot
4,4,# fourth plot
5,5, # 5th plot
7), # 7th plot)
nrow = 2, byrow = TRUE))
plot(1:5, type = "p")
plot(1:5, type = "l")
plot(1:5, type = "b")
boxplot(runif(100))
hist(1:100)
boxplot(runif(100), col = "red")
boxplot(runif(100), col = "blue")


