r - 添加多图轴

标签 r

为了生成具有多个图的布局,我有以下代码和一些虚拟图:

jpeg("/path/to/file",height=10000,width=5000)
plot.new()
par(mar=c(2,2,1,1), oma=c(2,4,0,0), xpd=NA)

for (i in 1:10) {

    par(mar=c(2,2,1,1),fig=c(0, 0.5, (10-i)/10, (11-i)/10), new=T)    
    matplot(rnorm(20)*sample(100,1),                                          
        col="blue",axes=F,type="l",lwd=10, xlab="",ylab="")

    par(mar=c(2,2,1,1),fig=c(0.5, 1, (10-i)/10, (11-i)/10), new=T)    
    matplot(rnorm(20)*sample(100,1),                                          
        col="red",axes=F,type="l",lwd=10, xlab="",ylab="")    
}
dev.off()

我想在跨越一列中所有 10 个图的远左轴和远右轴上添加一条垂直线/轴。由于我将使用这条线作为轴,因此我需要能够添加刻度线和标签。

最佳答案

您可以通过?axis?Axis来绘制轴。要在多个绘图上跨越轴,您必须重置 usr 坐标。

请在下面找到基本图形解决方案:

## store number of rows
nRow <- 10

## your example code 
## (only the number "10" is replaced by nRow and oma is adapted)
plot.new()

par(mar=c(2, 2, 1, 1), oma=c(2, 4, 0, 4), xpd=NA)

for (i in 1:nRow) {

    par(mar=c(2, 2, 1, 1), fig=c(0, 0.5, (nRow-i)/nRow, ((nRow+1)-i)/nRow), new=TRUE)    
    matplot(rnorm(20)*sample(100, 1),                                          
            col="blue", axes=F, type="l", lwd=10, xlab="", ylab="")

    par(mar=c(2, 2, 1, 1), fig=c(0.5, 1, (nRow-i)/nRow, ((nRow+1)-i)/nRow), new=TRUE)
    matplot(rnorm(20)*sample(100, 1),                                          
            col="red", axes=F, type="l", lwd=10, xlab="", ylab="")    
}

## define new user coordinates
usr <- c(0, 1, 0, 1) ## x1, x2, y1, y2

## calculate tick positons
## in general: (usr[3]+(diff(usr[3:4])/(nRow-1))*0:(nRow-1))
## but our usecase is much easier:
ticksAt <- 1/(nRow-1)*0:(nRow-1)

## choose left column and reset user plotting area (usr)
par(mar=c(2, 2, 1, 1), fig=c(0, 0.5, 0, 1), usr=usr, new=TRUE)
## draw axis; see ?Axis for details
Axis(side=2, at=ticksAt, labels=as.character(1:(nRow)), line=0.5)

## choose right column and reset user plotting area (usr, not needed because already done)
par(mar=c(2, 2, 1, 1), fig=c(0.5, 1, 0, 1), usr=usr, new=TRUE)
## draw axis; see ?Axis for details
Axis(side=4, at=ticksAt, labels=as.character((nRow+1):(2*nRow)), line=0.5)

关于r - 添加多图轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867283/

相关文章:

r - 没有不需要的列的内部连接 ​​data.table

r - 如何从 R 中另一个向量的值中提取数据集的行

R data.table内存高效的rbindlist

r - 如何在混合效应模型中获得系数及其置信区间?

r - 如何全选

r - 基于网络图相似度的前 10 位好友

r - ggplot2 ggsave 文本大小没有改变

r - 调色板没有返回正确的长度?

r - ggpubr不在ggdotchart中创建多个酒吧

R install.packages - 'curl' 调用具有非零退出状态