在 R 中对齐多个绘图轴

aligning multiple plot axes in R

我在 R 中有以下图,其中包含两个堆叠在一起的图:

time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)

layout(matrix(c(1,2,2), 3, 1, byrow=TRUE))

par(mar=c(1, 4, 4, 6) + 0.1)
othertime <- seq(0,48,12) 
otherbetagal <- c(0.05,0.18,0.25,0.31,0.32)
plot(othertime, 
     otherbetagal+c(0.13072000, -0.38438639, 0.16157348, 
                    -0.07862935, 1.72706526),
     xlim=c(0,70))

## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)

## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, xlab="", ylab="", 
     xlim=c(0,70),
     type="b",col="black", main="Mike's test data")
axis(2, col="black",las=1)  ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()

## Allow a second plot on the same graph
par(new=TRUE)

## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15,  xlab="", ylab="",  
     axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4) 
axis(4, col="red",col.axis="red",las=1)

## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)  

不幸的是,顶部 x 轴和底部 x 轴未对齐。我希望它们对齐。如果你仔细观察,刻度线很接近但没有对齐 - 即你不能从顶部绘图中的刻度“70”到底部绘图中的刻度“70”绘制一条垂直直线。如何解决?

如果将相同的 xlim 参数添加到第二个绘图,则 x 轴将对齐...

## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15,  xlab="", ylab="",  
     xlim=c(0,70),# same parameter as the first plot
     axes=FALSE, type="b", col="red")