4

I have been using R to maintain a rather large stack of raster layers (over 700 layers of data for sub-Saharan Africa). Each layer looks as follows http://hcapi.harvestchoice.org/v2.0/core/?varCode=SALUM&format=tif

I need to batch generate PNG images for print media, as well as thumbnails of the layers.

Using R raster package, I can easily plot each layer and apply custom color tables and legends. I run into problems when trying to generate small thumbnails with no title and axis (see an example below). I cannot find any option to have the raster plot occupy the full size of the graphic device, regardless of any graphic parameter I pass to par().

Here is reproducible code:

library(rgdal)
library(raster)

url <- "http://hcapi.harvestchoice.org/v2.0/core/?varCode=SALUM&format=tif"
download.file(url, "./r.zip", "curl")
unzip("r.zip")
r <- raster("./SALUMSSAtif.tif")
cc <- c("#AFF1E9", "#9ddfa3", "#87CD58", "#CDAF19", "#761200", "#94725F", "#D61F00")

png("./SALUMSSAtif.png", width=200, height=200)
par(mar=c(0,0,0,0), oma=c(0,0,0,0), xaxs="i", yaxs="i")
plot(r, col=cc, main=NULL, legend=F, axes=F)
dev.off()

This produces the attached plot that's badly off-center and too small. Any idea how to remove all the plot margins using raster::plot or another method?

thumbnail

Thanks, --Mel.

  • 1
    Never mind, I seem to have found a solution using raster::image instead. image(r, ylim=c(-40, 28), xlim=c(-20,58), xaxs="i", yaxs="i", col=cc) – mbacou May 29 '14 at 12:26
  • The difference is the defaults for asp. – mdsumner May 29 '14 at 13:26
2

As long as you've got a working installation of the gdalUtils package, you could use gdal_translate(), its thin wrapper around the GDAL function of the same name.

To make thumbnails that are 15% as large as the original image, for instance, you would do the following:

library(gdalUtils)
gdal_translate("SALUMSSAtif.tif", "SALUMSSA_thumb.tif", outsize=c("15%","15%"))

enter image description here

  • Also, if you want to enforce a certain width or height while keeping the aspect ratio constant, you should be able to do that with a bit of computation using the results of gdalInfo(), as in: "unlist(gdalinfo("SALUMSSAtif.tif", raw_output=FALSE)[c("rows", "columns")])" – Josh O'Brien May 29 '14 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.