An exercise based on a previous session. How to combine several graphs on one “page” in R?
# load the 'iris' data
data(iris)
# in base R To create a plot window for 2 graphs in two rows
par(mfrow = c(2, 2))
plot(Sepal.Length ~ Petal.Width, data = iris)
plot(Sepal.Length ~ Sepal.Width, data = iris)
hist(iris$Sepal.Length)
boxplot(Petal.Width ~ Species, data = iris)
# with ggplot: ggplot uses functionality that is provided from the
# 'grid'-family of packages
library(ggplot2)
library(gridExtra)
## Loading required package: grid
# create individual ggplot objects
p1 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Width, colour = Species)) +
geom_point()
p2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
geom_point()
p3 <- ggplot(iris, aes(x = Species, y = Sepal.Width)) + geom_boxplot()
# then arrange them together as one object
grid.arrange(p1, p2, main = "Two graphs")
grid.arrange(p1, p2, p3, main = "Three graphs")
grid.arrange(p1, p2, p3, main = "Three graphs in two rows", nrow = 2)
# how to get an empty element in the lower left? create a placeholder
blank <- grid.rect(gp = gpar(col = "white"))
# Nothing to see here!
grid.arrange(p1, p2, blank, p3, main = "Four graphs in two rows", nrow = 2)
To save the object use the code below. The pdf can later be opened by inkscape (http://inkscape.org/) or any other vector-based drawing program if not everything you want can be done in R itself.
pdf(file = "four_graphs.pdf", width = 9, height = 7)
grid.arrange(p1, p2, blank, p3, main = "Four graphs in two rows", nrow = 2)
dev.off()