Marc
Marc

Reputation: 661

Add vector world map to raster animation in R

I have created an animation with the animate function of the raster package and would like to add a vector map of the world on it.

This is my code where I create a raster brick from a 3D array of monthly mean temperatures before animating it:

r <- brick(ncols=nb.cols, nrows=nb.rows)
r <- setValues(r, monthly.mean)
animate(r)

The raster animation works great but how can I add a vector map of the world?

Many thanks

Upvotes: 3

Views: 1574

Answers (3)

Marc
Marc

Reputation: 661

Thank you! both methods worked like a charm!

A quick answer for those interested:

With saveHTML:

require(animation)
require(rgdal)
require(raster)

countries <- readOGR(dsn=".", layer="Countries")  # Shapefile of world countries

r <- brick(ncols=144, nrows=72)
r <- setValues(r, monthly.mean)          # monthly.mean is a 3D array 144x72x420

saveHTML({
  for(m in 1:420) {                      # serie of 420 months
    plot(r[[m]], zlim=c(min, max))       # min, max of the legend
    plot(countries, add=T)
  }
})

With FUN:

require(rgdal)
require(raster)

countries <- readOGR(dsn=".", layer="Countries")

r <- brick(ncols=144, nrows=72)
r <- setValues(r, monthly.mean)

fun <- function() {
  plot(countries, add=T)
}

animate(r, zlim=c(min, max), addfun=fun)

Upvotes: 4

Robert Hijmans
Robert Hijmans

Reputation: 47081

You can use the addfun argument

library(raster)
# example data
r <- raster(nrows=10, ncols=10)
s <- stack(replicate(10, setValues(r, runif(ncell(r)))))
xy <- cbind(-180 + runif(10) * 360, -90 + runif(10) * 180)

# create a function to add some vector data
fun <- function() {
    points(xy, cex=2)
    points(xy, pch=3, col='red')
}

# use it
animate(s, addfun=fun)

Upvotes: 3

Spacedman
Spacedman

Reputation: 94182

I doubt you can, but you can use the animation package to create a web page animation with play/stop/loop controls etc.

You will have to write a function to draw each frame of your animation with the raster layer and the vector map, and then you stick that in the saveHTML function of the animation package.

Example (not tested):

saveHTML( { for(f in 1:12){plot(r[[i]]; plot(world, add=TRUE)} })

should create an HTML file and open your browser to view it. To make this example work you will need a world vector object in the same coordinate system. You might also want to set the zlim when you plot the raster so the scale doesn't change.

Upvotes: 1

Related Questions