I know how to combine plots created by R graphics. Just do something like
attach(mtcars)
par(mfrow = c(3,1))
hist(wt)
hist(mpg)
hist(disp)
However, now I have plots by three different graphic systems
# 1
attach(mtcars)
boxplot(mpg~cyl,
xlab = "Number of Cylinders",
ylab = "Miles per Gallon")
detach(mtcars)
# 2
library(lattice)
attach(mtcars)
bwplot(~mpg | cyl,
xlab = "Number of Cylinders",
ylab = "Miles per Gallon")
detach(mtcars)
# 3
library(ggplot2)
mtcars$cyl <- as.factor(mtcars$cyl)
qplot(cyl, mpg, data = mtcars, geom = ("boxplot"),
xlab = "Number of Cylinders",
ylab = "Miles per Gallon")
The par
method doesn't work anymore. How can I combine them?
Combine multiple ggplots using ggarrange() We'll use nested ggarrange() functions to change column/row span of plots. For example, using the R code below: the line plot (lp) will live in the first row and spans over two columns.
Combine multiple ggplot on one page.Use the function ggarrange() [ggpubr package], a wrapper around the function plot_grid() [cowplot package]. Compared to plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.
To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used.
I have been adding support for these kinds of problems to the cowplot package. (Disclaimer: I'm the maintainer.) The examples below require R 3.5.0 and the latest development version of cowplot. Note that I rewrote your plot codes so the data frame is always handed to the plot function. This is needed if we want to create self-contained plot objects that we can then format or arrange in a grid. I also replaced qplot()
by ggplot()
since use of qplot()
is now discouraged.
library(ggplot2)
library(cowplot) # devtools::install_github("wilkelab/cowplot/")
library(lattice)
#1 base R (note formula format for base graphics)
p1 <- ~boxplot(mpg~cyl,
xlab = "Number of Cylinders",
ylab = "Miles per Gallon",
data = mtcars)
#2 lattice
p2 <- bwplot(~mpg | cyl,
xlab = "Number of Cylinders",
ylab = "Miles per Gallon",
data = mtcars)
#3 ggplot2
p3 <- ggplot(data = mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
xlab("Number of Cylinders") +
ylab("Miles per Gallon")
# cowplot plot_grid function takes all of these
# might require some fiddling with margins to get things look right
plot_grid(p1, p2, p3, rel_heights = c(1, .6), labels = c("a", "b", "c"))
The cowplot functions also integrate with the patchwork library for more sophisticated plot arrangements (or you can nest plot_grid()
calls):
library(patchwork) # devtools::install_github("thomasp85/patchwork")
plot_grid(p1, p3) / ggdraw(p2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With