R语言基础——layout()函数

简介

par()函数的mfrowmfcol 参数是较为常用的一页多图的方法,但是这两个参数的限制在于它们只能将图形区域拆分为网格状,每一格的长和宽都分别必须相等,而且每一格中必须有一幅图形,不能实现一幅图形占据多格的功能。

layout()函数突破了这种限制,接下来详细介绍。

layout()函数

用法

layout(mat, widths = rep.int(1, ncol(mat)),
       heights = rep.int(1, nrow(mat)), respect = FALSE)
  • mat 参数为一个矩阵,提供了作图的顺序以及图形版面的安排。0代表空缺,不绘制图形,大于0 的数代表绘图顺序,相同数字代表占位符。
  • widthsheights 参数提供了各个矩形作图区域的长和宽的比例。
  • respect 参数控制着各图形内的横纵轴刻度长度的比例尺是否一样。
  • n 参数为欲显示的区域的序号。

示例

1. 生成2行2列的版面,并设置宽度和高度。

par(oma = c(2,2,2,2))
layout(matrix(c(1, 2, 1, 3), 2), widths = c(1, 3), heights = c(1, 2))
layout.show(3)

在这里插入图片描述
在生成的版面上绘图。

hist(rnorm(100))
boxplot(1:10)
plot(1:10)

在这里插入图片描述
如果取消宽度和高度设置,则区域排版如下:

par(oma = rep(.5,4))
layout(matrix(c(1, 2, 1, 3), 2))
layout.show(3)
hist(rnorm(100))
boxplot(1:10)
plot(1:10)

在这里插入图片描述

2. layout()函数实现精细布局。

# 生成数据
x = pmin(3, pmax(-3, stats::rnorm(50)))
y = pmin(3, pmax(-3, x + runif(50, -1, 1)))
xhist = hist(x, breaks = seq(-3, 3, 0.5), plot = F)
yhist = hist(y, breaks = seq(-3, 3, 0.5), plot = F)
top = max(c(xhist$counts, yhist$counts))
# 布局
layout(matrix(c(2, 0, 1, 3), 2, 2, byrow = TRUE), c(3, 1), c(1, 3))
# 绘图
par(mar = c(2, 2, 1, 1))
plot(x, y, xlim = c(-3, 3), ylim = c(-3, 3), ann = FALSE,pch = 21,bg = "steelblue")
abline(lm(y ~ x),col = "red",lwd = 2)
par(mar = c(0, 2, 1, 1))
barplot(xhist$counts, axes = FALSE, ylim = c(0, top), space = 0)
par(mar = c(2, 0, 1, 1))
barplot(yhist$counts, axes = FALSE, xlim = c(0, top), space = 0, horiz = TRUE)

在这里插入图片描述


##侵权请联系作者删除!

参考书籍

[1] 现代统计图形

  • 7
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值