Wednesday, 26 August 2015

How to Show Multiple graphs together in R


Multiple graphs eh? You got it bruh!

In this post I am going to write about general methods that can be used to combine multiple graphs together.

Here again we are going to call our friend the par() function with its mfrow and mfcol super powers

Are you ready?...

So, lets start by understanding mfrow() [stress on row] and mfcol() [stress on column]

If the objective is to have a panel of graphs with 3 columns and 2 rows then the syntax will be as follows -

>par(mfrow=c(2,3))
or
>par(mfcol=c(2,3))

The above codes is essentially par(mfrow or col =c(number of rows,number of columns))

So yes, at a time you will only use mfrow() or mfcol(). mfrow() will simply fill the panels with graphs from left to right starting with first row, that is along the rows, and mfcol() will fill the panels with graphs from top to bottom starting with first column, that is along the columns.

Have a look at the panel -



If you are using mfrow(), the horny heart will be the second graph and if you are using mfcol(), the horny graph will be the third graph. Hope that helps :)

Lets take a simple example where we are going to plot four graphs in a grid of 2X2

>attach(mtcars)
> par(mfrow=c(2,2))
> plot(wt,mpg,main="scatter plot of wt vs mpg")
> plot(wt,disp,main="Scatter plot of wt vs disp")
> hist(wt,main="histogram of wt")
> boxplot(wt,main="boxplot of wt")
> detach(mtcars)

And this will produce the following plot -


let us repeat the same thing, but this time we will use mfcol(). And here is how the code will be -


> par(mfcol=c(2,2))
> plot(wt,mpg,main="scatter plot of wt vs mpg")
> plot(wt,disp,main="Scatter plot of wt vs disp")
> hist(wt,main="histogram of wt")
> boxplot(wt,main="boxplot of wt")
> detach(mtcars)

And here is how your result will be -


So, you can clearly compare the differences while using mfrow() and mfcol()

Hope this post was useful.

Till then,

Stay Awesome!

No comments:

Post a Comment