I am using R with cygwin and am trying to plot some basic graphics. Here is a simple example from one of Paul Murrell's papers:
library(grid)
x <- rnorm(50)
y <- x + rnorm(50, 1, 2)
rx <- range(x)
dx <- diff(rx)
ry <- range(y)
dy <- diff(ry)
max <- max(rx, ry)
min <- min(rx, ry)
r <- c(min(rx, ry), max(rx, ry))
d <- diff(r)
scale <- r + c(-1, 1) * d * 0.05
extscale <- c(min(scale), max(scale) + diff(scale) * 1/3)
lay <- grid.layout(2, 2,
widths = unit(c(3, 1), "inches"),
heights = unit(c(1, 3), "inches"))
vp1 <- viewport(w = unit(4, "inches"), h = unit(4, "inches"),
layout = lay, xscale = extscale, yscale = extscale)
grid.newpage()
pushViewport(vp1)
grid.rect()
grid.xaxis()
grid.text("Test", y = unit(-3, "lines"))
grid.yaxis()
grid.text("Retest", x = unit(-3, "lines"), rot = 90)
vp2 <- viewport(layout.pos.row = 2, layout.pos.col = 1,
xscale = scale, yscale = scale)
pushViewport(vp2)
grid.lines()
grid.points(x, y, gp = gpar(col = "blue"))
This plots fine. If however I add the following line to the program:
grid.lines(x, y, gp = gpar(col = "red"))
The lines are all over the place. I had expected that lines would connect the points in order. I have had a similar problem with some code I wrote but there the lines plot fine but the points do not.
Would appreciate any help. Thanks.
For some reason, grid.points() and grid.lines() have different "default units". (These are the units -- "native" and "npc" respectively -- that are used when you pass the functions a numeric vector without any associated units.)
args(grid.lines)
# function (x = unit(c(0, 1), "npc"), y = unit(c(0, 1), "npc"),
# default.units = "npc", arrow = NULL, name = NULL, gp = gpar(),
# draw = TRUE, vp = NULL)
args(grid.points)
# function (x = stats::runif(10), y = stats::runif(10), pch = 1,
# size = unit(1, "char"), default.units = "native", name = NULL,
# gp = gpar(), draw = TRUE, vp = NULL)
The quick solution is to explicitly set the default units for grid.lines() to match those used by grid.points():
grid.lines(x, y, gp = gpar(col = "red"), default.units = "native")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With