library(raster)
admin <- getData('GADM', country='FRA', level=2)
set.seed(123)
id <- data.frame(ID_2 = admin@data$ID_2, day1 = sample(1:20,96,replace = T),
day2 = sample(50:80,96,replace = T),
day3 = sample(120:140,96,replace = T),
day4 = sample(200:230,96,replace = T))
admin.shp <- merge(admin,id)
If I want to colour the plot using either day1
, day2
, day3
or day4
, I can do this:
plot(admin.shp, col = admin.shp@data$day1)
What I am trying to do is to produce some sort of .gif file or animation that goes from day 1 to day 230:
range <- c(min(id$day1),max(id$day4))
If the day matches values in day1
, the polygon should turn green,
If it matches in day2 that polygon should turn blue,
If it matches in day3 that polygon should turn orange,
If it matches in day4 that polygon should turn red
If I had to do this for a single column (for e.g. day1), I can do this:
library(magick)
c(min(id$day1),max(id$day1)) # 1, 20
for(i in 1:20){
breaks.pl <- c(0, i, 21)
col.pl <- c("green4","white")
cuts.pl <- cut(data.frame(admin.shp)[, "day1"],breaks = breaks.pl)
png(paste0(i,".png"), width = 1000, height = 600)
plot(admin.shp, col = col.pl[cuts.pl], border = 'transparent', main = paste0("day:",i))
plot(admin.shp, add = T)
dev.off()
}
This will produce a series of png files and I can then generate a .gif of these 20 png files to create an animation for day1
list.png <- list()
for(i in 1:20){
png.file <- image_read(path = paste0(i,".png"))
list.png[[i]] <- png.file
}
png.stack1 <- list.png[[1]]
for(i in 1:20){
png.stack <- list.png[[i]]
png.stack1 <- c(png.stack1,png.stack)
}
png.img <- image_scale(png.stack1)
png.ani <- image_animate(png.img, fps = 1, dispose = "previous")
image_write(png.ani, "my.animation.gif")
However, I want to extent this so that I use all the four columns day1
to day4
Adapted from your code, this should do the trick:
colors = c("white", "green4", "blue", "orange", "red")
library(animation)
ani.options(interval=.05)
i = 0
saveGIF({
for(k in 2:5){
while (i < max(id[,k])) {
print(i)
i = i + 1
breaks.pl <- c(0, i, max(id$day4)+1)
col.pl <- c(colors[k], colors[k-1])
cuts.pl <- cut(data.frame(id)[, k], breaks = breaks.pl)
plot(admin.shp, col = col.pl[cuts.pl], main = paste0("day:",i))
}
}
})
Demo: