结合由R base,lattice和ggplot2创建的图

nal*_*zok 7 graphics plot r ggplot2 lattice

我知道如何组合R图形创建的图.做一些像

attach(mtcars)
par(mfrow = c(3,1)) 
hist(wt)
hist(mpg)
hist(disp)
Run Code Online (Sandbox Code Playgroud)

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

# 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")
Run Code Online (Sandbox Code Playgroud)

par方法不再起作用.我该如何组合它们?

Cla*_*lke 8

我一直在为cowplot包添加对这些问题的支持.(免责声明:我是维护者.)以下示例需要R 3.5.0和牛皮图的最新开发版本.请注意,我重写了您的绘图代码,因此数据框始终传递给绘图函数.如果我们想要创建自包含的绘图对象,然后我们可以格式化或排列在网格中,则需要这样做.我也取而代之的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"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

cowplot功能还与拼凑库集成,以实现更复杂的绘图安排(或者您可以嵌套plot_grid()调用):

library(patchwork) # devtools::install_github("thomasp85/patchwork")
plot_grid(p1, p3) / ggdraw(p2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述