本文介绍组合多个图为整体一个图,使用par() 或 layout函数。
1. par()函数
使用par()函数,可以使用选项mfrow=c(nrows, nclos) 创建按行填充矩阵,mfcol=c(nrows, nclos) 按列填充。
# 1 figures arranged in 2 rows and 2 columns
attach(mtcars)
par(mfcol=c(2,2))
plot(wt,mpg, main="Scatterplot of wt vs. mpg")
plot(wt,disp, main="Scatterplot of wt vs disp")
hist(wt, main="Histogram of wt")
boxplot(wt, main="Boxplot of wt")
detach(mtcars)
再看一个示例:
# 2 figures arranged in 3 rows and 1 column
attach(mtcars)
par(mfrow=c(3,1))
hist(wt)
hist(mpg)
hist(disp)
detach(mtcars)
2. layout()函数
上面布局比较简单,layout可以实现复杂布局。首先我们看其参数:
- mat: 矩阵,其每个元素表示图形的位置
- widths: 表示列宽度的向量. 也可以使用lcm 函数精确设置
- heights: 表示列的高度向量,也可以使用lcm 函数精确设置
- respect: 布尔或矩阵,由与mat相同维度的0和1填充,以表示是否尊重宽度和高度之间的关系。
可以利用layout.show函数预览布局,方便我们理解:
l <- layout(matrix(c(1, 2, # First, second
3, 3), # and third plot
nrow = 2,
ncol = 2,
byrow = TRUE))
layout.show(l)
下面我们看一个示例,第一行放两个图,第二行放一个图:
mat <- matrix(c(1, 2, # First, second
3, 3), # and third plot
nrow = 2, ncol = 2,
byrow = TRUE)
layout(mat = mat)
# Data
set.seed(6)
x <- rexp(50)
plot(x) # First plot
boxplot(x) # Second plot
hist(x) # Third plot
下面示例,定义两行,第一行放一个图形,第二行放两个图形,且比第一行高三倍:
# 设置边缘空间
par(mar = c(1, 1, 1, 1))
mat <- matrix(c(1, 1, # First
2, 3), # second and third plot
nrow = 2, ncol = 2,
byrow = TRUE)
layout(mat = mat,
heights = c(1, 3)) # First and second row
# relative heights
# Data
set.seed(6)
x <- rexp(50)
plot(x) # First row
boxplot(x) # Second row, left
hist(x) # Second row, right
我们再看一个示例,生成两列布局,左边放一个图形,右边放两个图形,且右边列宽度是左边两倍:
mat <- matrix(c(1, 2, # First, second
1, 3), # first and third plot
nrow = 2, ncol = 2,
byrow = TRUE)
layout(mat = mat,
widths = c(1, 2)) # First and second
# column relative widths
# Data
set.seed(6)
x <- rexp(50)
plot(x) # First column, top
boxplot(x) # First column, bottom
hist(x) # Second column
3. 组合使用
使用layout函数也可以结合边缘控制,需要对每个图参数进行设置:
mar 指定数值向量 c(bottom, left, top, right) ,指定图的四个边缘空间,缺省为 c(5, 4, 4, 2) + 0.1。
# Data
set.seed(6)
x <- rexp(50)
# 这里0表示保留空白,不放置图形
layout(matrix(c(2, 0, 1, 3),
nrow = 2, ncol = 2,
byrow = TRUE),
widths = c(3, 1),
heights = c(1, 3), respect = TRUE)
# Top and right margin of the main plot
par(mar = c(5.1, 4.1, 0, 0))
plot(x)
# Left margin of the histogram
par(mar = c(0, 4.1, 0, 0))
hist(x, main = "", bty = "n",
axes = FALSE, ylab = "")
# Bottom margin of the boxplot
par(mar = c(5.1, 0, 0, 0))
# Boxplot without plot region box
par(bty = "n")
# Boxplot without axes
boxplot(x, axes = FALSE)