Adding grid nodes to the native coordinate system
I create numbers lattice
and annotate them with a batch grid
. To set the coordinates for my shapes, I also use the unit()
related functions from the package grid
. This often helps to add units together and this is usually not a problem. But I find there is a strange problem when I try to add my own units and the x- and y-scales for the current viewport do not have a bottom border of 0. Here's a small example:
library(grid)
library(lattice)
# Expected result
xyplot(0:10 ~ 0:10, ylim=c(0,10))
myVP <- seekViewport("plot_01.panel.1.1.vp")
y1 <- unit(5, "native") + unit(2.5, "native")
convertY(y1, "native") # 7.5native, as expected
# Strange result
xyplot(10:20 ~ 0:10, ylim = c(10:20))
myVP <- seekViewport("plot_01.panel.1.1.vp")
y2 <- unit(10, "native") + unit(5, "native")
convertY(y2, "native") # 5native (why not 15native?)
# Other results with same lattice plot are as expected
convertY(unit(10, "npc") + unit(5, "npc"), "npc") # 15npc
convertY(unit(10, "mm") + unit(5, "mm"), "mm") # 15mm
convertY(unit(10, "native") + unit(5, "mm"), "native") # ~10.35native
Further research shows what unit()
subtracts min(ylim)
when it is added to native units. So, in this example, I expect to unit(10, "native") + unit(5, "native")
give unit 15native
, but it will indeed give unit (15-10) native.
Why does adding unit work this way with its own coordinate system, and why does it work differently with other coordinate systems?
source to share
Josh O'Brien points to the answer in his comments, and Paul Murrell "locndimn vignette" (run vignette("locdimn")
provides details. Magnitude, as unit(5, "native")
has one meaning if it refers to a location in a coordinate system, and another meaning if it refers to a dimension. Murrell rule is that "locations are added as vectors and dimensions are added as lengths" and this seems to be to account for the results I got when adding units to the native coordinate system.
Specifically, in my example, using convertHeight
gives the result that I expected:
library(lattice)
xyplot(10:20 ~ 0:10, ylim = c(10:20))
myVP <- seekViewport("plot_01.panel.1.1.vp")
y2 <- unit(10, "native") + unit(5, "native")
convertY(y2, "native") # 5native
convertHeight(y2, "native") # 15native
source to share