简体   繁体   中英

How to save after overlaying a spatial point data frame onto raster

I tried to overlay a SpatialPointsDataFrame (yellow birds) onto a raster data (map). This was successful with the following R codes:

map1 = plot(map)

overlay_map = plot(yellowbirds,add=TRUE,col="blue")

However, when I want to regenerate the map by typing overlay_map , the output produced is Null instead of giving me the map.

How do I save the above correctly as a variable, so that I can generate the map without typing out the code again?

It is difficult to help you without any reproducible example.

However, if you only want to save the plot, you could do something like:

map1 <- plot(map)

overlay_map <- recordPlot()  #To save the next plot into an object

plot(yellowbirds,add=TRUE,col="blue")

Then, simply call the object again:

overlay_map

recordPlot is the right way to go, only that it saves the current plot (see ?recordPlot ) into a variable. I created this reproducible example :

library(raster)
map <- raster(system.file("external/test.grd", package="raster"))
yellowbirds <- SpatialPoints(
  coords = structure(c(179025.023681718, 179606.015156299, 179878.354910009, 
                       180441.19040101, 180913.245974108, 330055.067887591, 330508.967477108, 
                       331398.610672561, 331743.574360594, 332342.721818756), 
                     .Dim = c(5L, 2L), .Dimnames = list(NULL, c("x", "y"))))

plot(map)
map1 <- recordPlot()
plot(yellowbirds, add = TRUE)
overlay_map <- recordPlot()

在此处输入图片说明

Now we kill the current devices and reproduce the two plots:

dev.off()
map1
dev.off()
overlay_map

Both the map as well as the overlay_map should be recreated in the empty device. Even if you rm(map1) , overlay_map will plot correctly.

NOTE: Do not call plot(overlay_map) as it produces the following error

Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' is a list, but does not have components 'x' and 'y'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM