Open In App

Combining Plots in R

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There might be some situations for a data analyst to look at different plots at a time and need to produce results using them. In this article, we are going to discuss how to combine plots in R programming. This can be achieved using the par() method.

Syntax: par(mfrow,mfcol,layout())

where,

  • mfrow –  used to determine the value of the grid as (no_of_rows,no_of_cols) and is going to plot row-wise
  • mfcol – used to determine the value of the grid as (no_of_columns,no_of_rows) and is going to plot column wise
  • layout() – used to customize the layout of the combined plot. [The main attribute to this is the matrix(mat) of length rows + columns and the plots positions]

Row Wise Combined Plot using mfrow 

In this, we will create the plot of 2 plots and combine them row-wise.

R




# Creation of sample data frame
df<- data.frame(roll_number=c(1,2,3,4,5,6,7,8,9,10),
                marks=c(23,30,21,24,27,28,23,30,29,26))
 
# Combining the plot using par function
par(mfrow=c(2,1))
 
# Plotting scatter plot
plot(df$roll_number, df$marks,
     main="Scatterplot",
     xlab="Roll Number", ylab="Marks")
# Plotting Histogram
hist(df$marks, main="Histogram", xlab="Marks")


Output:

Combining Plots in R

 

Column Wise Combined Plot using mfcol

In this, we will create the plot of 2 plots and combine them column-wise.

R




# Combining the plot using par function
par(mfcol=c(1,2))
 
# Plotting scatter plot
plot(df$roll_number, df$marks,
     main="Scatterplot",
     xlab="Roll Number", ylab="Marks")
# Plotting Histogram
hist(df$marks, main="Histogram", xlab="Marks")


Output:

Combining Plots in R

 

Layout Customized Combined Plot

We can also customize the layout of the combined plot using the layout() function and then plot accordingly. Let’s see an example for that.

R




# Combining the plots using par() function
par(mfrow=c(2,2),layout(c(1,3,3,2)))
 
# Customizing the layout of the combined plot
l2 <- layout(matrix(c(3,3,1,2),
                   nrow = 2,
                   ncol = 2,
                   byrow = TRUE))
 
# Plotting the ScatterPlot
plot(df$roll_number,df$marks,main="Scatterplot",
     xlab="Roll Number",ylab="Marks")
 
# Plotting the Boxplot
boxplot(df$marks, main="Boxplot")
 
# Plotting the Histogram
hist(df$marks, main="Histogram",xlab="Marks")


Output:

Combining Plots in R

 

To display the layout of the plot, we can use layout.show().

R




# Customizing the layout of the combined plot
l <- layout(matrix(c(3,3,1,2),
                   nrow = 2,
                   ncol = 2,
                   byrow = TRUE))
 
# To display the layout as specifies in matrix
layout.show(l)


Output:

Combining Plots in R

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads