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

标签 r plot ggplot2 graphics lattice

我知道如何组合由 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方法不再有效。我怎样才能把它们结合起来?

最佳答案

我一直在向 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"))

enter image description here

cowplot 函数还与 patchwork 库集成以进行更复杂的绘图安排(或者您可以嵌套 plot_grid() 调用):
library(patchwork) # devtools::install_github("thomasp85/patchwork")
plot_grid(p1, p3) / ggdraw(p2)

enter image description here

关于r - 组合由 R base、lattice 和 ggplot2 创建的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012553/

相关文章:

r - 如何向 nlm 提供梯度(或 hessian)?

向量元素的递归操作

json - 将 R 表转换为 JSON 字符串

python-2.7 - Pandas 简单的 X Y 图

r - 考虑ggplot2中不同因素的调整回归线

r - ggplot2密度绘制R中不同大小的数据

r - ggplot - 用直线连接极坐标中的点

r - 具有两个 Y 轴的 ggplot

python - 如何在matplotlib中对x轴上的日期格式进行舍入

r - 如何在ggplot中给QQ图上的点着色