This project uses NTL data from years 2000-2019, to build an animated lava map of China. This data uses Chen, 2021 enxtended NTL series. data : https://essd.copernicus.org/articles/13/889/2021/
First we set our paths and stack with the raster package.
We then build our custom colour palette for the later plots.
We then build a loop for each .tif file, and use ggplot2 to plot.
path <- find_rstudio_root_file()
files.url <- paste0(path, ".Data")
files <- list.files(path=files.url, full.names = TRUE)
sg = stack(files)
# colour palette
mycols <- c("#710000","#AA0000","#FF1900","#FFA700","#FFD900","#FFF250", "#FFFFFF")
# Loop to create plots for each image
sapply(files, function(x){
im_name <- gsub("\\.[A-z]+$", "", x) #img_name
Year <- str_extract(x, "[0-9]{4}") #Title
# Load image as raster
im <- raster::raster(x)
# Transform to df
NTL_df <- as.data.frame(im, xy=T) # Creating a df
colnames(NTL_df) <- c("x", "y", "NTL")
NTL_df[NTL_df == 0] <- NA #remove 0 for efficiency
NTL_df <- na.omit(NTL_df)
gg_NTL <- NTL_df %>%
ggplot() +
geom_raster(aes(x = x, y = y, fill = NTL)) + #raster
scale_fill_gradientn(colours = mycols, trans="log", name="Nightime lights")+ #colour scale
borders("world", "China", colour = "grey", size=0.1) + #China border
labs(title=Year, caption="data : https://essd.copernicus.org/articles/13/889/2021/") + # Insert Year and reference
theme(
legend.position = c(0.9, 0.4),
legend.key.height = unit(0.2,"cm"),
legend.key.width = unit(0.1,"cm"),
legend.title=element_text(color="white", size=4),
text = element_text(color = "white", size = 4),
plot.background = element_rect(fill = "black", color = NA),
panel.background = element_rect(fill = "black", color = NA),
legend.background = element_rect(fill = "black", color = NA),
plot.title = element_text(size= 13, hjust=0.1, color = "white", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
) +
coord_quickmap()
# Save plot
ggsave(paste0(im_name, ".png"),
dpi = 300)
})
And finally we load all created Figs, and combine using the Magick package. We can then animate as shown below.
# Create gif
# List plots files
path <- find_rstudio_root_file()
files.url <- paste0(path, "./DATA/NTL_LONG/")
plots <- list.files(path=files.url, pattern = ".png", full.names = T)
# Read the plots as image
plots_list <- lapply(plots, image_read)
# Join the list of plots
plot_joined <- image_join(plots_list)
# Create animation, defining the frames per second (fps)
plot_animated <- image_animate(plot_joined, fps = 1)
plot_animated