Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r convert raster stack or brick to an animation

Tags:

r

ggplot2

raster

I have downloaded some NetCDF files of land use scenario results from http://luh.umd.edu/data.shtml. Each file at this location has values for 11 land use types with annual values from 2015 to 2100. I'd like to make an animated gif or movie that shows the changes over time. This seems like it should be straightforward but I've tried a variety of routes, none of which work, so I'm hoping for some that actually work. 1. One approach involves creating a raster stack or brick of one of the land use variables using the stack or brick functions from the raster package. then using the raster animate function. Unfortunately, I get the following error message "animation of RasterLayer [stack, brick] objects not supported".

  1. Another option is to convert each year of the land use data into a SpatialPixelDataFrame and then into a data.frame, use ggplot to create a gif and then combine the gifs into an animated gif. But this process seems extremely convoluted.

An R script that contains my current efforts to do this is here.

like image 557
JerryN Avatar asked Dec 31 '22 13:12

JerryN


2 Answers

Having a look through your code, I can make the code below work.

Basically, I'm making a big dataframe with data for all years.

mydf <- purrr::map_dfr(
  as.list(ncin.brick), 
  ~setNames(as.data.frame(as(., "SpatialPixelsDataFrame")), c('value', 'x', 'y')), 
  .id = 'year'
)

gg <- ggplot(
  mydf, 
  aes(x = x, y = y, fill = value)
) +
  geom_sf(data = borders, fill = "transparent", color = "black", inherit.aes = FALSE) +
  geom_tile() +
  scale_fill_viridis_c() +
  ggthemes::theme_map()

gganim <- gg + transition_time(as.numeric(year)) #+ labs(title = "Year: {frame_time}")

gganim

The picture below is the result (animation is subtle).

enter image description here

like image 134
Axeman Avatar answered Jan 14 '23 03:01

Axeman


Try raster::animate(), there are several incompatible animate functions across packages and this seems like a clash.

I usually animate using a loop to plot raster slices, and capture that using the animate package, e.g. with saveHTML().

For ggplot2 see the gganimate package, but it doesn't scale well given the need to expand the data out.

like image 39
mdsumner Avatar answered Jan 14 '23 02:01

mdsumner