Is there a way to ensure that the box around a plot matches the raster extents exactly? In the following there is a gap above and below or to the left and right of the raster depending on the device proportions:
require(raster)
r = raster()
r[]= 1
plot(r, xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r)))
One element of the problem with raster objects is that asp=1 to ensure proper display. The following basic scatterplot has the same issue when asp=1:
plot(c(1:10), c(1:10), asp=1)
Try vectorplot(r) from the rasterVis package to see what I want the axes to look like.
EDIT:
Solutions need to play nice with SpatialPoints overlays, not showing points outside the specified raster limits:
require(raster)
require(maptools)
# Raster
r = raster()
r[]= 1
# Spatial points
x = c(-100, 0, 100)
y = c(100, 0, 100)
points = SpatialPoints(data.frame(x,y))
plot(r, xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r)))
plot(points, add=T)
You’d probably do best to go with one of the
lattice-based functions for plotting spatial raster objects provided by therasterandrasterVispackages. You discovered one of them invectorplot(), butspplot()orlevelplot()better match your needs in this case.(The
base graphics-basedplot()method for"RasterLayer"objects just doesn’t allow any easy way for you to set axes with the appropriate aspect ratio. For anyone interested, I go into more detail about why that’s so in a section at the bottom of the post.)As an example of the kind of plot that
levelplot()produces:Either of these methods may still plot some portion of the symbol representing points that fall just outside of the plotted raster. If you want to avoid that possibility, you can just subset your
SpatialPointsobject to remove any points falling outside of the raster. Here’s a simple function that’ll do that for you:Additional weedy detail about why it’s hard to make
plot(r)produce snugly fitting axesWhen
plotis called on an object of typeraster, the raster data is (ultimately) plotted using eitherrasterImage()orimage(). Which path is followed depends on: (a) the type of device being plotted to; and (b) the value of theuseRasterargument in the originalplot()call.In either case, the plotting region is set up in a way which produces axes that fill the plotting region, rather than in a way that gives them the appropriate aspect ratio.
Below, I show the chain of functions that’s called on the way to this step, as well as the call that ultimately sets up the plotting region. In both cases, there appears to be no simple way to alter both the extent and the aspect ratio of the axes that are plotted.
useRaster=TRUEuseRaster=FALSE