Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ploting artefact with points over raster

I noticed some weird behavior when resizing the plot window. Consider

library(sp)
library(rgeos)
library(raster)
rst.test <- raster(nrows=300, ncols=300, xmn=-150, xmx=150, ymn=-150, ymx=150, crs="NA")
sap.krog300 <- SpatialPoints(coordinates(matrix(c(0,0), ncol = 2)))
sap.krog300 <- gBuffer(spgeom = sap.krog300, width = 100, quadsegs = 20)
shrunk <- gBuffer(spgeom = sap.krog300, width = -30)
shrunk <- rasterize(x = shrunk, y = rst.test)
shrunk.coords <- xyFromCell(object = rst.test, cell = which(shrunk[] == 1))
plot(shrunk)
points(shrunk.coords, pch = "+")

If you resize the window, plotted points get different extent compared to the underlying raster. If you resize the window and plot shrunk and shrunk.coords again, the plot turns out fine. Can anyone explain this?

like image 222
Roman Luštrik Avatar asked May 12 '11 11:05

Roman Luštrik


1 Answers

If you plot directly with the RasterLayer method for plot the resize problem does not occur.

## gives an error, but still plots 
raster:::.imageplot(shrunk)
points(shrunk.coords, pch = ".")

So it must be something in the original plot call before the .imageplot method is called.

 showMethods("plot", classes = "RasterLayer", includeDefs = TRUE)

It does occur if we call raster:::.plotraster directly, and this is the function that calls raster:::.imageplot:

raster:::.plotraster(shrunk, col = rev(terrain.colors(255)), maxpixels = 5e+05)
points(shrunk.coords, pch = ".")

It is actually in the axis labels, not the image itself. See with this, this plots faithfully on resize:

 raster:::.imageplot(shrunk)
 abline(h = c(-80, 80), v = c(-80, 80))

But do it like this, and the lines are no longer at [-80, 80] after resize:

plot(shrunk)
abline(h = c(-80, 80), v = c(-80, 80))

So it is actually the points plotted after the raster that are showing incorrectly: the plot method keeps the aspect ratio fixed, so widening the plot doesn't "stretch" out the raster circle to an ellipse. But, it does something to the points that are added afterwards so the calls to par() must not be handled correctly (probably in raster:::.imageplot).

Another way of seeing the problem is to show that axis() does not know the space being used by the plot, which is the same problem you see when overplotting:

plot(shrunk)
axis(1, pos = 1)

When you resize the x-axis length the two axes are no longer synchronized.

like image 94
mdsumner Avatar answered Oct 11 '22 11:10

mdsumner