tobiasegli_te tobiasegli_te - 1 month ago 16
R Question

R: absolute coordinates in grid package

In the grid package, per default the x- and y-positions in a new viewport range between 0 and 1 (relative to width / height of the viewport).
In order to plot values I have to transform the values to a range between 0 and 1:

library(grid)

vect1 <- rnorm(20)
vect1_relative <- vect1-min(vect1)
vect1_relative <- vect1_relative/max(vect1_relative)

vect2 <- rnorm(20)
vect2_relative <- vect2-min(vect2)
vect2_relative <- vect2_relative/max(vect2_relative)

pushViewport(viewport())
grid.lines(x = c(0,1),y = c(0,1))
grid.points(x = vect1_relative,y = vect2_relative)


I'm sure there is a more straightforward solution and I assume it has to do with using
unit()
while opening the viewport, but I haven't figured out yet how.
Can someone show me an example how to use absolute values (and define xlim / ylim) in grid viewports?

Answer

One option is to use dataViewport and native units.

library(grid)

d <- data.frame(x=100*rnorm(10),y=1e4*rnorm(10))
grid.newpage()
pushViewport(viewport(width=0.8,height=0.8))
grid.rect(gp=gpar(fill="grey98"))
vp <- dataViewport(xData = d$x, yData = d$y)
grid.points(d$x, d$y, default.units = "native", vp=vp, 
            pch=19, size = unit(0.2,"char"))

enter image description here