我知道如何组合由 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"))
cowplot 函数还与 patchwork 库集成以进行更复杂的绘图安排(或者您可以嵌套
plot_grid()
调用):library(patchwork) # devtools::install_github("thomasp85/patchwork")
plot_grid(p1, p3) / ggdraw(p2)
关于r - 组合由 R base、lattice 和 ggplot2 创建的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012553/