作者:庄闪闪
在同一页面上混合多个图形是一种常见的做法。
它可以在同一数字上总结大量信息,例如,它被广泛用于科学出版物。
一页多图用mfrow参数或mfcol参数规定,这也是我几年前经常用的一种方法。
x <- rnorm(50)
y <- rnorm(50,2,2)
随便模拟产生数据,并对数据绘制一些简单的图,用该函数将一页中对他们进行全部展示。
par(mfrow=c(2,2))
plot(x, y, xlab = "", ylab = "")
hist(x,main='')
qqnorm(x,main = '');qqline(x)
barplot(x, axes = FALSE, space = 0,col='white')
layout(mat, widths = rep.int(1, ncol(mat)),
heights = rep.int(1, nrow(mat)), respect = FALSE)
生成2行2列的版面,并设置宽度和高度。par()中oma参数指四个外边空的行数
par(oma = c(2,2,2,2))
nf <- layout(matrix(c(1,2,1,3),2,2),widths = c(1, 3), heights = c(1, 2))
layout.show(nf)
再将各个图进行填充
plot(x, y, xlim = xrange, ylim = yrange, xlab = "", ylab = "")
barplot(xhist$counts, axes = FALSE, ylim = c(0, top), space = 0)
barplot(yhist$counts, axes = FALSE, xlim = c(0, top), space = 0, horiz = TRUE)
前面两种方法,说实话可以实现,但是比较费劲。那么下面看看gridExtra包。
gridExtra包让混合多个图片变得轻而易举。它提供了grid.arrange() 函数来完成 这个任务。它的nrow参数允许指定如何安排布局。
对于更复杂的布局,arrangeGrob() 函数允许做一些嵌套。这里有 4 个 例子来说明 gridExtra 是如何工作的:
library(ggplot2)
library(gridExtra)
这里我们用ggplot绘图,并存在变量名称(g1,g2,g3)中,然后用grid.arrange()将各个变量名称展现出来。
# Make 3 simple graphics:
g1 <- ggplot(mtcars, aes(x=qsec)) + geom_density(fill="slateblue")
g2 <- ggplot(mtcars, aes(x=drat, y=qsec, color=cyl)) + geom_point(size=5) + theme(legend.position="none")
g3 <- ggplot(mtcars, aes(x=factor(cyl), y=qsec, fill=cyl)) + geom_boxplot() + theme(legend.position="none")
g4 <- ggplot(mtcars , aes(x=factor(cyl), fill=factor(cyl))) + geom_bar()
# Plots
grid.arrange(g1, g2, g3, nrow = 3)
当然可以使用参数arrangeGrob(),下面绘制了两行,第一行是g2,第二行是g3,g4.
grid.arrange(g2, arrangeGrob(g3, g4, ncol=2), nrow = 2)
下面绘制了两行,第一行是g2,第二行是g3,g4,g1.
grid.arrange(g2, arrangeGrob(g3, g4, g1,ncol=3), nrow = 2)
[1]
《R语言教程》——李东风
[2]
R Graphical Representation – Multiple Plots in One Graph
[3]
http://lightonphiri.org/blog/r-graphical-representation-multiple-plots-in-one-graph
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有