I have this R code to produce multipanel plots with NetCDF files that contain monthly values (12 layers per .nc files). This code produces a colourbar as the one showed below, however I would like to have triangle-shaped edges for all values greater than a threshold (at the top) and all values less than a threshold at the bottom. How can I do this in R using the poly.image function?
# Read NetCDF file
file.nc <- nc_open("tas_EUR-11_ECMWF-ERAINT_r1i1p1_ALADIN53_merged_1990_2008_CEL_ymonmean.nc")
lat <- ncvar_get(file.nc, "lat")
lon <- ncvar_get(file.nc, "lon")
t2 <- ncvar_get(file.nc, "tas") # Dimensions: lon x lat x month
nc_close(file.nc)
# Compute global min/max across all months
global_min <- min(t2, na.rm = TRUE)
global_max <- max(t2, na.rm = TRUE)
max_abs_value <- max(abs(global_min), abs(global_max))
#
# Define breaks manually
num_colors <- 35
breaks <- seq(global_min, global_max, length.out = num_colors + 1)
#
zlim <- c(-max_abs_value, max_abs_value) # Set symmetric limits
# Save multiplot to a single PNG file
dpi <- 150
png("tas_multiplot.png", width = 28 * dpi, height = 24 * dpi, res = dpi)
# Set up 3 columns × 4 rows layout
par(mfrow = c(4, 3), mar = c(3, 3, 3, 8), oma = c(0, 0, 7, 0))
mnths = c("January","February","March", "April","May","June","July","August","September","October","November","December")
rwb <- colorRampPalette(c("purple","blue","deepskyblue3","skyblue1","white","lightcoral","red2","violetred4","yellow3"))
# Loop through each month
for (month in 1:12) {
cat("Processing month:", month, "\n")
# Extract the layer for the current month
t2_month <- t2[,,month]
# Plot temperature data
poly.image(
x = lon, y = lat, z = t2_month,
col = rwb(35),
zlim = c(global_min, global_max),
main = mnths[month],
cex.main=2.5,
)
# Add world map overlay
map("worldHires", fill = FALSE, add = TRUE, col = "grey50", lwd = 0.6, interior = TRUE)
map("worldHires", fill = FALSE, add = TRUE, col = "black", lwd = 1, interior = FALSE)
map.grid(c(-180, 180, -90, 90), nx = 36, ny = 18, labels = FALSE, col = "grey10", lwd = 0.8, lty = 3)
}
mtext("Temperature - Model 1", outer = TRUE, cex = 2.5, font = 2)
breaks <- seq(-max_abs_value, max_abs_value, length.out = 36)
lbls <- round(breaks, 2)
# Plot the color bar in the last column
#par(mar = c(35, 5, 5, 12)) # Adjust margins for the color bar
image.plot(
zlim = c(global_min, global_max),
col = rwb(35),
legend.only = TRUE,
legend.width = 6,
legend.shrink = 5,
horizontal = FALSE,
cex.labels = 15,
breaks = breaks,
labels = lbls,
axis.args = list(cex.axis = 2.5),
smallplot = c(0.9, 0.93, 0.1, 1)
)
dev.off() # Save the PNG file