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
andmfcol
: 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 themfrow
value and by columns as per themfcol
value.
If we setmfcol = c(2,3)
, there will be columns and rows. Conversely, ifmfrow = c(2,3)
, there will be rows and columns. -
mar
: This specifies the margins of the plotting region in inches. The default value isc(5, 4, 4, 2) + 0.1
, which means lines of margin at the bottom, lines on the left and right, and 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 themain
title and axis labels. The default value isc(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>))
plot(<column1>,<column2>)
plot(<column3>,<column4>)
Let’s practice. You can change the values in the example below to better understand the functionality.
Get hands-on with 1400+ tech skills courses.