Search code examples
rimageresolutionrasterprojection

R: How is it possible to export from R an image from a raster layer while maintaining image resolution?


I have been attempting to export a geographic raster layer which is projected in terms of the Lambert Conformal Conic projection (with a resolution of 1000 m by 1000 m) as an image file (e.g. as an *.eps) after having plotted it with some overlaid points (which is straightforward enough), but upon opening the image after export, it is clear that it has a resolution of a lesser quality than the aforementioned.

I've been using the 24 Bioclimate layers downloadable from: https://sites.ualberta.ca/~ahamann/data/climatewna.html. Here is an example of one of those layers (which was saved as a *.tif), and its resolution:

enter image description here Below is the section of the script I have been running which is of relevance:

> projection <- raster("prediction.grd")
> projection

class       : RasterLayer 
dimensions  : 3132, 2359, 7388388  (nrow, ncol, ncell)
resolution  : 1000, 1000  (x, y)
extent      : -3594000, -1235000, 4703000, 7835000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=lcc +lat_1=49 +lat_2=77 +lat_0=0 +lon_0=-95 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
data source : C:\Users\User\Documents\Project\prediction.grd 
names       : layer 
values      : 7.006775e-12, 0.001495079  (min, max)

> plot(projection, col = colorPalette(14, "jc"), colNA = 'black', axes = FALSE); 
> points(train_locality_points, col='white', pch=15, cex=0.2)

Following the running of this code, I've gone about exporting the plot generated via the 'export' dropdown menu of R Studio to save it as an image with an extension that can be viewed outside of R instead of as a file with its original extension or something similar. I can open the image which is saved, but it evidently is not of the same quality as what the resolution of the layer is stated as above.

The image below is one I've saved in the way just described. To illustrate the trouble I've been having, Vancouver Island ( i.e. the large one with many white dots clustered at its southern end) is about 500 kilometres in length, which should correspond to about 500 pixels in the image if the resolution were 1 km by 1 km as the raster layer is. In this image the length of the island is represented by about a fifth of that number (...yes, I counted).

enter image description here

Any help as to how this issue could be remedied I would greatly appreciate. Thank-you for taking the time to read through and consider this question.


Solution

  • To get an image with same resolution as RasterLayer r, you can do

    png('file.png', height=nrow(r), width=ncol(r)) 
    plot(r, maxpixels=ncell(r))
    dev.off()