更新:在 R wiki http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes 上复制的材料,链接现已损坏:也可从 the wayback machine 获得
同一图上有两个不同的 y 轴
(一些材料最初由 Daniel Rajdl 2006/03/31 15:26)
请注意,很少有适合在同一个地块上使用两种不同比例尺的情况。很容易误导图形的查看者。检查以下两个关于此问题的示例和 cmets(example1、example2 来自Junk Charts)以及this article by Stephen Few(其结论是“我当然不能一劳永逸地得出结论,即轴从来没有用过;只是我想不出有什么情况可以根据其他更好的解决方案来保证它们。”)另请参阅this cartoon 中的第 4 点 ...
如果你确定了,基本的方法是创建你的第一个图,设置par(new=TRUE)以防止R清除图形设备,使用axes=FALSE创建第二个图(并将xlab和ylab设置为为空白 - ann=FALSE 也应该可以工作)然后使用 axis(side=4) 在右侧添加一个新轴,并使用 mtext(...,side=4) 在右侧添加一个轴标签。这是一个使用一些虚构数据的示例:
set.seed(101)
x <- 1:10
y <- rnorm(10)
## second data set on a very different scale
z <- runif(10, min=1000, max=10000)
par(mar = c(5, 4, 4, 4) + 0.3) # Leave space for z axis
plot(x, y) # first plot
par(new = TRUE)
plot(x, z, type = "l", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("z", side=4, line=3)
plotrix 包中的twoord.plot() 会自动执行此过程,latticeExtra 包中的doubleYScale() 也是如此。
另一个例子(改编自 Robert W. Baer 的 R 邮件列表帖子):
## set up some fake test data
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)
## 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, ylim=c(0,1), xlab="", ylab="",
type="b",col="black", main="Mike's test data")
axis(2, ylim=c(0,1),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="", ylim=c(0,7000),
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, ylim=c(0,7000), 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)
## Add Legend
legend("topleft",legend=c("Beta Gal","Cell Density"),
text.col=c("black","red"),pch=c(16,15),col=c("black","red"))
类似的配方可用于叠加不同类型的图 - 条形图、直方图等。