-->

Convert units from npc to native using grid in R

2020-04-06 01:10发布

问题:

The core of my problem:

I'm attempting to convert npc units to native units using the grid package's convertUnit, convertX and convertY functions. (npc=normalized parent coordinates, possibly known as ndc units, normalized device coordinates to some in base graphics R. I'm trying to get to native units, those in which the plot is graphed, so in terms of the xlim and ylim units.) However when I attempt to do this as such:

> xyplot(1:10~1:10)
> convertX(unit(.9, "npc"), "native")
[1] 484.2native

when I'm expecting a number close to 9 as the native x coordinate. It appears convertX is returning units in device coordinates/pixels instead.

Reasoning: I'm trying to use a base locator type device to return npc coordinates, and from those npc coordinates convert to the native coordinates in which the graph was plotted. While I can use base graphics' locator or grid.locator, I'm trying to extend the functionality of this new, non blocking locator to grid/lattice graphics by converting from npc back to native. convertUnit and convertY don't work either.

Question Is it possible for grid to convert from npc back to the active plotting window's native coordinates? Why is convertX returning pixels rather than native coordinates?

Thanks much in advance.

Edited for tags and sloppy mistake leaving out xyplot before. My apologies, but it holds with xyplot.

回答1:

‘"native"’ Locations and dimensions are relative to the viewport's ‘xscale’ and ‘yscale’. The conversions occur within the current viewport.

> plot(1:10)
> convertX(unit(.9,"npc"),"native")
[1] 453.6native
> pushViewport(viewport())
> convertX(unit(.9,"npc"),"native")
[1] 0.9native
> convertX(unit(.1,"npc"),"picas")
[1] 4.21575picas #making window smaller
> convertX(unit(.1,"npc"),"picas")
[1] 1.9798375984252picas #making window larger
> convertX(unit(.1,"npc"),"picas")
[1] 5.25783218503937picas

So you need a viewport first to get sensible values out.



回答2:

Apparently, after the viewport is pushed, it has forgotten about the set coordinate of the underlying plot and the new coordinates seem to be equivalent to the npc coordinates.

Until you plot into the new viewport, after which you are back to square one:

xyplot(1:10 ~ 10:1)
> convertX(unit(.9, "npc"), "native")
[1] 605.7native
> pushViewport(viewport())
> convertX(unit(.9, "npc"), "native")
[1] 0.9native
> xyplot(1:10 ~ 10:1)
> convertX(unit(.9, "npc"), "native")
[1] 605.7native

Is it possible to obtain coordinates that correspond to those in which x and y are actually plotted?