Last active
March 5, 2017 08:43
Save a plot for each observation then make a video out of it! Full article at: https://firsttimeprogrammer.blogspot.com/2017/03/resizing-spatial-data-in-r.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load required libraries | |
require(dplyr) | |
require(raster) | |
require(rasterVis) | |
require(ncdf4) | |
# Clean workspace | |
rm(list = ls()) | |
# Open nc file and get the data | |
a <- nc_open("qnet_2008.nc") | |
qnet <- ncvar_get(a, "qnet") | |
lon <- ncvar_get(a, "lon") | |
lat <- ncvar_get(a, "lat") | |
time <- ncvar_get(a, "time") | |
nc_close(a) | |
# Generate the expanded grid | |
grd <- expand.grid(lon, lat, time) | |
# Set names | |
names(grd) <- c("lon", "lat", "time") | |
# Put the data for qnet in a dataframe | |
vdata <- data.frame(qnet = as.numeric(qnet)) %>% tbl_df() | |
# Bind with the grid | |
data_ <- grd %>% tbl_df() %>% bind_cols(vdata) | |
# Set levels for levelplot | |
lvls <- pretty(range(na.omit(data_$qnet)), 50) | |
# Remove variables not needed anymore | |
rm(a, qnet, lon, lat, grd, vdata) | |
# Loop over the number of days and save a picture for each day | |
for(i in 1:length(time)) | |
{ | |
# Get the data for the current day | |
current_data <- data_ %>% filter(time == i) | |
# Generate the raster | |
x <- raster(nrows = 180, ncol = 360, | |
ymn = min(current_data["lat"]), | |
ymx = max(current_data["lat"]), | |
xmn = min(current_data["lon"]), | |
xmx = max(current_data["lon"])) | |
# Assign values to the raster | |
values(x) <- as.vector(unlist(current_data["qnet"])) | |
# Flip the raster to get the correct plot | |
x <- flip(x, direction = "y") | |
# Level plot | |
plt <- levelplot(x, contour = FALSE, par.settings = RdBuTheme, at = lvls) | |
print(plt) | |
# Save the plot | |
dev.copy(png, paste("plot_2008_", i, ".png", sep = "")) | |
dev.off() | |
# Print day | |
print(i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment