Skip to content

Instantly share code, notes, and snippets.

@mick001
Last active March 5, 2017 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mick001/88c0242356e21963f1ca5d7ce94134b7 to your computer and use it in GitHub Desktop.
Save mick001/88c0242356e21963f1ca5d7ce94134b7 to your computer and use it in GitHub Desktop.
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
# 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