0

I have spatial data in R, let's say an object of formal class SpatialPointsDataFrame but the below problem is encountered with Raster too.

I can plot easily the data with spplot() and save a .png file. If I want to create and store a function to recall this operation (since I have to repeat this many times in a simulation), spplot() save an empty .pgn file UNLESS I use dev.off() outside the function.

# example data
trees <- data.frame(x=runif(100, 1,100), y=runif(100, 1,100), value=runif(100, 20,60))
trees <- SpatialPointsDataFrame(trees[,c("x","y")], trees)
proj4string(trees) <- CRS("+proj=utm +zone=30 ellps=WGS84")

# simple plotting, it works
png(filename="spplot0.png", width = 480, height = 480, units = "px")
spplot(trees, "value")
dev.off()

# create functions
map1 <- function(){
  png(filename="spplot1.png", width = 480, height = 480, units = "px")
  spplot(trees, "value")
  dev.off()
}

map2 <- function(){
  png(filename="spplot2.png", width = 480, height = 480, units = "px")
  spplot(trees, "value")
}

# carry out functions. map1() save an empty image.
map1()
map2();dev.off()

Why map1() does not work and map2()+dev.off() outside does?

I know there are alternative mapping options (plot, spplot, ggplot) but I wish to stick with spplot() for this job. I have already found a work-around solution (see function map2) but it baffles me, my code gets more cluttered and I fear to encounter more problems in the future.

1

You have to call print() inside the function:

map1 <- function(){
  png(filename="spplot1.png", width = 480, height = 480, units = "px")
  print(spplot(trees, "value"))
  dev.off()
}

map1() # works

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.