组合由 R base、lattice 和 ggplot2 创建的图

Combining plots created by R base, lattice, and ggplot2

我知道如何组合由 R 图形创建的绘图。只需做类似

的事情
attach(mtcars)
par(mfrow = c(3,1)) 
hist(wt)
hist(mpg)
hist(disp)

但是,现在我有三种不同图形系统的绘图

# 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")

par 方法不再有效。如何组合它们?

请参阅此问题的答案中描述的使用 gridBase 的方法:R: How should I create Grid-graphics?

library(grid)
library(gridBase)
library(lattice)
library(ggplot2)

grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 3)))

# base graphics
vp <- pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 1))
par(omi = gridOMI())
boxplot(mpg ~ cyl,
        xlab = "Number of Cylinders",
        ylab = "Miles per Gallon", data = mtcars)
popViewport()

# lattice plot
vp <- pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2))
par(fig = c(0.9, 1, 0.6, 0.9))
p <- bwplot(~ mpg | cyl,
            xlab = "Number of Cylinders",
            ylab = "Miles per Gallon",
            data = mtcars)
print(p, vp = vp, newpage = FALSE)
popViewport()

# ggplot
vp <- pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 3))
mtcars$cyl <- as.factor(mtcars$cyl)
p <- qplot(cyl,
           mpg,
           data = mtcars,
           geom = ("boxplot"),
           fill = cyl,
           xlab = "Number of Cylinders",
           ylab = "Miles per Gallon")
print(p, vp = vp, newpage = FALSE)
popViewport()

我一直在为 cowplot 包添加对这类问题的支持。 (免责声明:我是维护者。)下面的示例需要 R 3.5.0 和 cowplot 的最新开发版本。请注意,我重写了您的绘图代码,因此数据框始终交给绘图函数。如果我们想要创建独立的绘图对象,然后我们可以格式化或排列在网格中,则需要这样做。我还将 qplot() 替换为 ggplot(),因为现在不鼓励使用 qplot()

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"))

cowplot 函数还与 patchwork 库集成,用于更复杂的情节安排(或者您可以嵌套 plot_grid() 调用):

library(patchwork) # devtools::install_github("thomasp85/patchwork")
plot_grid(p1, p3) / ggdraw(p2)