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. plot() save the correct graph, spplot() an empy one. 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. Thanks!