正如@joran 所说,grid 图形系统可以更灵活地控制单个设备上多个绘图的排列。
这里,我先用grconvertY()查询y轴上高度为50的位置以“标准化设备坐标”为单位。 (即作为绘图设备总高度的比例,0=底部,1=顶部)。然后我使用 grid 函数来:(1)推送一个填充设备的viewport; (2) 在grconvertY() 返回的高度绘制一条线。
## Create three example plots
par(mfrow=c(1,3))
barplot(VADeaths, border = "dark blue")
barplot(VADeaths, border = "yellow")
barplot(VADeaths, border = "green")
## From third plot, get the "normalized device coordinates" of
## a point at a height of 50 on the y-axis.
(Y <- grconvertY(50, "user", "ndc"))
# [1] 0.314248
## Add the horizontal line using grid
library(grid)
pushViewport(viewport())
grid.lines(x = c(0,1), y = Y, gp = gpar(col = "red"))
popViewport()
编辑:@joran 询问如何绘制一条从第一个图的 y 轴延伸到第三个图的最后一个条形边缘的线。这里有几个选择:
library(grid)
library(gridBase)
par(mfrow=c(1,3))
# barplot #1
barplot(VADeaths, border = "dark blue")
X1 <- grconvertX(0, "user", "ndc")
# barplot #2
barplot(VADeaths, border = "yellow")
# barplot #3
m <- barplot(VADeaths, border = "green")
X2 <- grconvertX(tail(m, 1) + 0.5, "user", "ndc") # default width of bars = 1
Y <- grconvertY(50, "user", "ndc")
## Horizontal line
pushViewport(viewport())
grid.lines(x = c(X1, X2), y = Y, gp = gpar(col = "red"))
popViewport()
最后,这是一个几乎等效的、更普遍有用的方法。它使用了 @mdsumner 的答案中链接到的文章中 Paul Murrell 演示的函数 grid.move.to() 和 grid.line.to():
library(grid)
library(gridBase)
par(mfrow=c(1,3))
barplot(VADeaths); vps1 <- do.call(vpStack, baseViewports())
barplot(VADeaths)
barplot(VADeaths); vps3 <- do.call(vpStack, baseViewports())
pushViewport(vps1)
Y <- convertY(unit(50,"native"), "npc")
popViewport(3)
grid.move.to(x = unit(0, "npc"), y = Y, vp = vps1)
grid.line.to(x = unit(1, "npc"), y = Y, vp = vps3,
gp = gpar(col = "red"))