Search code examples
rplot

Arranging odd number of plots in base R


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 you can use layout, which will create a matrix for you to map the figures to - here you will want 2 rows of 6 spaces each to make things even. The numbers in matrix(...) can be conceptualized as the plot number (1 = first plot, etc and note that 0 = no plot) and the number of times they repeat is the number of spaces they take up :

    layout(matrix(c(1,1, # first plot (covers top spaces 1-2)
                    2,2, # second plot (covers top spaces 3-4)
                    3,3, # third plot (covers top spaces 5-6)
                    0, # blank (covers bottom space 1 (0 = blank plot)
                    4,4,# fourth plot (covers bottom spaces 2-3)
                    5,5, # 5th plot (covers bottom spaces 4-5)
                    0), # blank (covers bottom space 6)
                    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)
    

    enter image description here

    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:

    (1) With all 12 spaces shown (6x2):

    enter image description here

    (2) With the five plot layout, where each plot takes up 2 spaces:

    enter image description here

    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")
    

    enter image description here