Subplots in R

Learn how to create more than one chart in the output.

We'll cover the following

In data analysis, we frequently need to create more than one chart to compare different datasets side by side, which may help us spot useful trends and patterns.

Also, we use supplementary charts to provide additional information to our audience. This helps us to convey our story in a more comprehensive style.

Subplots in base R

We use the par() function before the plot functions to output different charts next to each other. It allows us to design a layout for the charts that we will create. We use the plot functions after the par() function as usual. Here are the arguments that the function can take:

  • mfrow and mfcol: These set the layout of the plotting region in terms of rows and columns. The plots are filled into the matrix by rows as per the mfrow value and by columns as per the mfcol value.
    If we set mfcol = c(2,3), there will be 22 columns and 33 rows. Conversely, if mfrow = c(2,3), there will be 22 rows and 33 columns.

  • mar: This specifies the margins of the plotting region in inches. The default value is c(5, 4, 4, 2) + 0.1, which means 55 lines of margin at the bottom, 44 lines on the left and right, and 22 lines at the top. We can adjust these values to control the size and aspect ratio of the plotting region.

  • oma: This specifies the outer margins of the plot in inches. This includes the space for the main title and axis labels. The default value is c(0, 0, 0, 0), but we can adjust it to add more space for titles, labels, or other annotations.

The par() function only creates a layout for the charts, meaning that it does not get involved in the internal chart settings.

# Syntax structure 
par(mfrow = c(<row_number>,<column_number>), mar = c(<bottom>,<left>, <right>,<top>), oma = (<bottom>,<left>, <right>,<top>))

Let’s practice. You can change the values in the example below to better understand the functionality.

Get hands-on with 1200+ tech skills courses.