添加多绘图轴

时间:2012-06-03 01:37:12

标签: 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()

我想在远LHS和远RHS上添加垂直线/轴,该RHS跨越列中的所有10个图。由于我将此行用作轴,我需要能够添加刻度和标签。

2 个答案:

答案 0 :(得分:3)

您可以按?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)

答案 1 :(得分:0)

您可以制作整个设备的整体图,在那里添加轴,然后使用subplot函数(TeachingDemos包)在大图中绘制图。