Sunday, April 29, 2012

Multiple Plots on a Single Graph using ggplot2


I was trying to put multiple plots on a single graph using ggplot2; however,
It turned out that R built in par(mfrow=c(2,2)) doesn't work for ggplot2.
When I searched online i found this POST that illustrates how to do that.

It is very simple. For ggplot2, instead of using par(mfrow=c(2,2)), you need to use grid.arrange( graph1, graph2...., ncol=2)
However, grid.arrange() is a function of a package called "gridExtra", so first you have to install
gridExtra package.

Here are some examples based on our survey data (you can copy the following code) :-

install.packages("gridExtra")
library(gridExtra)
graph1 <-  qplot(Ind7_Confidence, data=myIndices, geom= "histogram", color=I("blue"),
fill=I("orange"),main="Software Use")


graph2 <- qplot(Ind5_WeightedMathAbility, data=myIndices, geom= "histogram", color=I("blue"),
fill=I("skyblue"),main="Weighted Math Ability")


graph3 <-qplot(Ind2_UnderstandingDataAna, data=myIndices, geom= "histogram", color=I("blue"),
fill=I("yellow"),main="Understanding Data Analysis")


graph4 <- qplot(Ind4_PractQuanMethod, data=myIndices, geom= "histogram", color=I("blue"),
fill=I("red"),main="Practical Quant Experience")
grid.arrange( graph1, graph2,graph3,graph4, ncol=2)
savePlot(filename="Gridhist.png",type="png")


Another Example using Density Plot

graph1 <- qplot(Ind7_Confidence, data=myIndices, geom="density",
fill = TwoPlusComputers, alpha = I(0.2),xlab="Data Analysis Confidence")


graph2 <- qplot(Ind8_ComSocialUse, data=myIndices, geom="density",
fill = TwoPlusComputers, alpha = I(0.2),xlab="Computer For Social Use")


graph3 <- qplot(Ind3_PractQualMethod, data=myIndices, geom="density",
fill = TwoPlusComputers, alpha = I(0.2),xlab="Practical Experience of Quant Methods")


graph4 <- qplot(Ind9_ComWorkUse, data=myIndices, geom="density",
fill = TwoPlusComputers, alpha = I(0.2),xlab="Computer For Prof Use")
grid.arrange( graph1, graph2, graph3,graph4, ncol=2)
savePlot(filename="GridDensity.png",type="png")




Adil 

1 comment: