组合由R基本,晶格和ggplot2创建的图 [英] Combining plots created by R base, lattice, and ggplot2

查看:79
本文介绍了组合由R基本,晶格和ggplot2创建的图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何组合由R图形创建的图.做类似的事情

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

par方法不再起作用.我怎样才能将它们结合起来?

The par method doesn't work anymore. How can I combine them?

推荐答案

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

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

cowplot函数还与拼凑程序库集成在一起,以实现更复杂的绘图安排(或者您可以嵌套plot_grid()调用):

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)

这篇关于组合由R基本,晶格和ggplot2创建的图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆