R Programming - Multiple Plots In One Graph
Hi there. In this post, the focus is on having multiple plots in one graph in the programming language R. The main R package that is used here is gridExtra. The main reference is http://lightonphiri.org/blog/ggplot2-multiple-plots-in-one-graph-using-gridextra. The original version of this post can be found on my website here.
A good reference for ggplot2 in R is the R Graphics Cookbook by Winston Chang.

Before entering in the main code, make sure to load in the ggplot2 and gridExtra packages into R. For installation of a R package use install.packages('pkg_name').
library(ggplot2)
library(gridExtra)
Simulating Normal Random Variables Plot
For the first plot, I simulate 10000 standard normal random variables (mean of 0 and variance of 1) in R. Most of the values will lie within +3 standard deviations from the mean of 0. Values outside of 3 standard deviations are extreme cases or outliers.
The results are plotted in ggplot2 in the form of a histogram.
# Normals Plot:
normals <- rnorm(n = 10000, mean = 0, sd = 1)
norm_plot <- ggplot(data = NULL, aes(normals)) +
geom_histogram(binwidth = 0.1, boundary = 2, col = "black", fill = "#D5ADA4") +
labs(x = "\n Number Of Standard Deviations (Z-Scores)", y = "Count \n", title = "Simulated Standard Normal Variates\n") +
theme(plot.title = element_text(hjust = 0.5, size = 13, face = "bold", colour = "darkgreen"),
axis.title.x = element_text(face="bold", colour="#6f0000", size = 12),
axis.title.y = element_text(face="bold", colour="#6f0000", size = 12))
# Show normals plot:
norm_plot
Simulating Exponential Random Variables Plot
In the second plot, I simulate 10000 exponential random variables in R with the rexp() function with the rate of 3.
# Exponential Plot:
exponentials <- rexp(n = 10000, rate = 3)
exps_plot <- ggplot(data = NULL, aes(exponentials)) +
geom_histogram(binwidth = 0.1, boundary = 2, col = "black", fill = "#b7b700") +
labs(x = "\n Value Of Exponential Random Variable", y = "Count \n", title = "Simulated Exponential Random Variables \n") +
theme(plot.title = element_text(hjust = 0.5, size = 13, face = "bold", colour = "darkgreen"),
axis.title.x = element_text(face="bold", colour="#6f0000", size = 12),
axis.title.y = element_text(face="bold", colour="#6f0000", size = 12))
# Show exponentials plot:
exps_plot
Multiple Graphs In One With grid.arrange()
From the gridExtra package in R, multiple plots can be put into one graph with the use of the grid.arrange() function. I put both the normal and exponential random variables plot into one with ncol = 2.
# Two plots in one:
grid.arrange(norm_plot, exps_plot, ncol = 2)
Having plots side by side makes things easier for the viewer and is good for comparisons.