如何为R语言中2×2布局的图形添加行标题
问题描述
我创建了一个2×2布局的图形,其中列代表两个不同变量,行代表两个不同地点。请问如何为这两行添加对应的地点名称?
示例代码:
library(biwavelet) par(mfrow = c(2,2), oma = c(3,3,0,0) + 0.1, mar = c(1,1,1,1) + 0.1) dat <- as.data.frame(matrix(nrow = 500, ncol = 2)) dat[1] <- seq(1,500) dat[2] <- sin(dat[1]) # top-left figure plot(wt(dat), xaxt = 'n', xlab = "", cex.axis = 1.5, cex.lab = 1.5) axis(1, at = seq(0, 500, by = 100), cex.axis = 0.1, col.axis = 'NA') title("Variable 1", line = 0.1, cex.main = 1.5) # top-right figure dat[2] <- sin(dat[1]*.5) plot(wt(dat), xaxt = 'n', col.axis = 'NA', xlab = "", ylab = "") axis(1, at = seq(0, 500, by = 100), cex.axis = 0.1, col.axis = 'NA') title("Variable 2", line = 0.1, cex.main = 1.5) # bottom-left figure dat[2] <- sin(dat[1]*.25) plot(wt(dat), cex.axis = 1.5) # bottom-right figure dat[2] <- sin(dat[1]*.125) plot(wt(dat), col.axis = 'NA', ylab = "", xlab = "") axis(1, at = seq(0, 500, by = 100), cex.axis = 1.5) title(xlab = "Time (hours)", ylab = "Period", outer = TRUE, line = 1.5, cex.lab = 1.5)
理想效果:
解决方案
可以通过调整图形外边界宽度,再用mtext()函数在布局左侧添加地点名称,具体操作如下:
先修改全局绘图参数,扩大左侧外边界(
oma)的宽度,避免地点名称被遮挡:
将原代码中的par(mfrow = c(2,2), oma = c(3,3,0,0) + 0.1)替换为:par(mfrow = c(2,2), oma = c(3,6,0,0) + 0.1, # 增大左侧外边界空间 mar = c(1,1,1,1) + 0.1)在所有绘图完成后,添加两行的地点名称:
使用mtext()指定左侧(side=2)、使用外边界(outer=TRUE),并通过at参数定位到对应行的垂直中心位置:# 添加地点名称,可根据显示效果微调at参数值 mtext("地点A", side = 2, outer = TRUE, line = 3, cex = 1.5, las = 1) mtext("地点B", side = 2, outer = TRUE, line = 3, at = 0.25, cex = 1.5, las = 1)
完整修改后的代码:
library(biwavelet) par(mfrow = c(2,2), oma = c(3,6,0,0) + 0.1, # 调整左侧外边界宽度 mar = c(1,1,1,1) + 0.1) dat <- as.data.frame(matrix(nrow = 500, ncol = 2)) dat[1] <- seq(1,500) dat[2] <- sin(dat[1]) # top-left figure plot(wt(dat), xaxt = 'n', xlab = "", cex.axis = 1.5, cex.lab = 1.5) axis(1, at = seq(0, 500, by = 100), cex.axis = 0.1, col.axis = 'NA') title("Variable 1", line = 0.1, cex.main = 1.5) # top-right figure dat[2] <- sin(dat[1]*.5) plot(wt(dat), xaxt = 'n', col.axis = 'NA', xlab = "", ylab = "") axis(1, at = seq(0, 500, by = 100), cex.axis = 0.1, col.axis = 'NA') title("Variable 2", line = 0.1, cex.main = 1.5) # bottom-left figure dat[2] <- sin(dat[1]*.25) plot(wt(dat), cex.axis = 1.5) # bottom-right figure dat[2] <- sin(dat[1]*.125) plot(wt(dat), col.axis = 'NA', ylab = "", xlab = "") axis(1, at = seq(0, 500, by = 100), cex.axis = 1.5) title(xlab = "Time (hours)", ylab = "Period", outer = TRUE, line = 1.5, cex.lab = 1.5) # 添加两行的地点名称 mtext("地点A", side = 2, outer = TRUE, line = 3, cex = 1.5, las = 1) mtext("地点B", side = 2, outer = TRUE, line = 3, at = 0.25, cex = 1.5, las = 1)
这样就能在布局左侧对应行的位置添加地点名称,和理想效果匹配。
内容的提问来源于stack exchange,提问作者tassones
相关产品推荐
相关产品推荐

