在R中对齐多个绘图轴

时间:2015-02-10 04:43:20

标签: r graphics plot statistics

我在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”。怎么修好?

1 个答案:

答案 0 :(得分:1)

如果将相同的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")