Combining Plots in R
Last Updated :
27 Mar, 2023
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
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))
par (mfrow= c (2,1))
plot (df$roll_number, df$marks,
main= "Scatterplot" ,
xlab= "Roll Number" , ylab= "Marks" )
hist (df$marks, main= "Histogram" , xlab= "Marks" )
|
Output:
Column Wise Combined Plot using mfcol
In this, we will create the plot of 2 plots and combine them column-wise.
R
par (mfcol= c (1,2))
plot (df$roll_number, df$marks,
main= "Scatterplot" ,
xlab= "Roll Number" , ylab= "Marks" )
hist (df$marks, main= "Histogram" , xlab= "Marks" )
|
Output:
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
par (mfrow= c (2,2), layout ( c (1,3,3,2)))
l2 <- layout ( matrix ( c (3,3,1,2),
nrow = 2,
ncol = 2,
byrow = TRUE ))
plot (df$roll_number,df$marks,main= "Scatterplot" ,
xlab= "Roll Number" ,ylab= "Marks" )
boxplot (df$marks, main= "Boxplot" )
hist (df$marks, main= "Histogram" ,xlab= "Marks" )
|
Output:
To display the layout of the plot, we can use layout.show().
R
l <- layout ( matrix ( c (3,3,1,2),
nrow = 2,
ncol = 2,
byrow = TRUE ))
layout.show (l)
|
Output:
Share your thoughts in the comments
Please Login to comment...