1

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.

asked Aug 18, 2017 at 11:25
1

1 Answer 1

2

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
answered Aug 18, 2017 at 12:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.