-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGithub_ERL_Paper.Rmd
457 lines (379 loc) · 27.5 KB
/
Github_ERL_Paper.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
---
title: 'Plotting for Manuscript: Seasonal Forecast Skill In Decision Variables'
author: "Ashish Kondal"
date: "04/09/2024"
output:
pdf_document: default
html_document: default
---
#-------------------------------------------------------------------------------
## SETUP - STARTING WITH FRESH ENVIRONMENT AND CONSOLE
#-------------------------------------------------------------------------------
```{r setup, include=FALSE}
knitr::opts_chunk$set(fig.width = 12, fig.height = 8, fig.path ='Figs/',echo = FALSE, warning = FALSE, message = FALSE)
cat("\014") # Clear console
rm(list = ls()) # Clearing the Environment and saved variable
```
## Installing Packages
#install.packages("dplyr")
#install.packages("data.table")
#install.packages("tidyverse")
#install.packages("pracma")
#install.packages("GGally")
#install.packages("reshape2")
#install.packages("Metrics")
#install.packages("ggpubr")
#install.packages("swfscMisc")
#install.packages("sf")
#-------------------------------------------------------------------------------
## LOADING PACKAGES
#-------------------------------------------------------------------------------
```{r Loading Packages, include = FALSE, echo = FALSE, warning=FALSE}
library(readr)
library(knitr)
library(dplyr)
library(tidyverse)
library(ggplot2)
library(sf)
library(stringr)
```
#-------------------------------------------------------------------------------
## INPUT SETUP - DEFINE VARIABLES AND DIRECTORIES
#-------------------------------------------------------------------------------
```{r Input setup, echo=FALSE}
# Setting the working directory
wd <- setwd("YOUR INPUT PATH")
input_dir <- paste(wd,"/sample_data/", sep="") # Setting input directory
output_dir <- paste(wd,"/sample_data/output/", sep="") # Setting output directory to store files and final images
if (!dir.exists(paste(output_dir, sep=""))){ # check if output directory already exists or not.
dir.create(paste(output_dir, sep="")) } # Create output directory if not already exists
# Provide file path to the shapefiles
huc6_shapefile_address <- paste(wd,"/Shapefiles/PNW_Shapefile_USonly/pnw_shapefile_USonly.shp", sep="") # PNW's shapefile at HUC06 Level
wa_shapefile_address <- paste(wd,"/Shapefiles/WA_Shapefile/WA_State_Boundary.shp", sep="") # Shapefile of Washington state
or_shapefile_address <- paste(wd,"/Shapefiles/OR_Shapefile/Oregon.shp", sep="") # Shapefile of Oregon state
id_shapefile_address <- paste(wd,"/Shapefiles/Idaho_shapefile/GU_StateOrTerritory.shp", sep="") # Shapefile of Idaho state
# Reading shapefiles
wa_shp = st_read(wa_shapefile_address)
or_shp = st_read(or_shapefile_address)
id_shp = st_read(id_shapefile_address)
huc6_shp = st_read(huc6_shapefile_address)
```
## 1. PNW's elevation dataset (Figure 1)
#-------------------------------------------------------------------------------
## EXTRACTING ELEVATION DATASET FOR US PORTION OF PNW (Figure 1)
#-------------------------------------------------------------------------------
```{r Extracting Elevation Data }
# Reading elevation dataset
elev_inputfilename <- paste(wd,"/sample_data/PNW_Elevation.txt",sep="") # path to elevation file
elevation <- read_csv(file = elev_inputfilename,col_names = TRUE, show_col_types = FALSE) # Reading elevation file
# Extracting elevation data for the US portion of the PNW region
HSS_inputfilename <- paste(input_dir, "GridWise_Tercile_HeidkeSkillScore_Fall_Fertilization_InitMonth_09_PNW_BothThreshold_NDJF.txt",sep="") # Reading one of the skill metric files to get the spatial extent of PNW.
HSS_data <- read_csv(file = HSS_inputfilename, col_names = TRUE, show_col_types = FALSE) # Reading above file
merged_data <- merge(HSS_data,elevation,by=c("Lat","Lon")) # Merging elevation and skill metric data to remove all the grids that are not present in the skill metric file
# Saving the extracted elevation data in a text file for plotting in arcmap
elevation <- dplyr::select(merged_data,c("cell_id","Lat","Lon","Elevation")) # select columns to save memory
elev_outputfilename <- paste(output_dir,"PNW_Elevation_inMeters_forUSportionOnly.txt",sep="") # Output elevation file name
write_csv(x = elevation, file = elev_outputfilename , append = FALSE, col_names = TRUE) # Saving the elevation data for plotting later in arcmap.
rm(HSS_data,HSS_inputfilename,merged_data)
```
# Plot the elevation data (elev_outputfilename) in ArcMap
## 2. PNW's Cropland Grids (Figure 1)
#-------------------------------------------------------------------------------
## PNW's CROPLAND - IRRIGATED & NON-IRRIGATED GRIDS (Figure 1)
#-------------------------------------------------------------------------------
```{r Cropland Grids}
# Reading the vegetation file
vegetation_file <- paste(wd,"/sample_data/PNW_crop_coverage_with_area_2024.txt",sep="")
vegetation <- read_csv(file=vegetation_file,col_names = TRUE, show_col_types = FALSE)
# Filter the irrigated and non-irrigated crop grids separately
veg_irrg <- filter(vegetation,(Crop_Code >= 100 & Crop_Code <10000))
veg_nonirrg <- filter(vegetation,(Crop_Code >= 10000))
# Saving the above data in separate text files - Plot in Arcmap
veg_irrg_outputfilename <- paste(output_dir,"PNW_Irrigated_Croplands.txt",sep="")
veg_nonirrg_outputfilename <- paste(output_dir,"PNW_Non_Irrigated_Croplands.txt",sep="")
write_csv(x = veg_irrg, file = veg_irrg_outputfilename, append = FALSE, col_names = TRUE)
write_csv(x = veg_nonirrg, file = veg_nonirrg_outputfilename, append = FALSE, col_names = TRUE)
```
# Plot the irrigated and non-irrigated croplands in ArcMap
#-------------------------------------------------------------------------------
## Forecast Skill in Fall Fertilization Application Decision (Figure 3)
#-------------------------------------------------------------------------------
```{r Plotting HSS of Fall Fertilizer Application for NDJF season on HUC 06 level, echo=FALSE, warning = FALSE}
# Removing previous runs data/variable
if (exists('dfdata') == TRUE){
rm(dfdata)
}
# Running code for forecast initialized in November (11), October, September (9) and August (8)
for (init in c(11,10,9,8)){
# Path to Heidke skill output file
HSS_inputfilename <- paste(input_dir, "HUC06_Tercile_HeidkeSkillScore_Fall_Fertilization_InitMonth_0",init,"_PNW_BothThreshold_NDJF.txt",sep="")
# Check if file exists in the input directory or not
if (file.exists(HSS_inputfilename) == FALSE){
text0 <- paste("File Does not Exist !",HSS_inputfilename)
print(text0)
}else{
# Reading input file and removing NA's if any
HSS_data <- read_csv(file = HSS_inputfilename,col_names = TRUE, show_col_types = FALSE)
HSS_data <- na.omit(HSS_data)
# Converting Initialization Month into Lead-Month
lookt <- c(0,0,0,0,0,-5,-4,-3,-2,-1,0,0) # Look out table
init1 = lookt[init] # Based on the look out table, initialization month is converted into lead month.
HSS_data['Init'] <- factor(init1)
# Creating new variable to append HSS data for all initialization together
if (exists('dfdata') != TRUE){ # if 'dfdata' doesn't exist, create this variable and save the HSS file's data in it.
dfdata <- HSS_data
rm(HSS_data)
}else{ # if 'dfdata' already exist, append the HSS file's data from other intializations to it.
dfdata <- rbind(dfdata,HSS_data) # This is the reason, we ensured that 'dfdata' shouldn't exists (if exists for any reason, remove it) at the beginning of this code chunk.
rm(HSS_data)
}
}
}
dfdata$Init <- factor(dfdata$Init, levels = c(0,-1,-2,-3)) # Factoring the lead months and ordering them for plotting purposes
# Select desired columns for the data and rename it for the plotting purposes
dfdata <- dplyr::select(dfdata,c("Init","HUC06_Name","Below 33rd Percentile","Above 67th Percentile"))
colnames(dfdata) <- c("Init","Name","Forecast of Cold Winters","Forecast of Warm Winters")
# Format the data in long format for easy plotting using "facet_grid"
dfdata_short <- dfdata %>% pivot_longer(!c("Name","Init"),names_to="Group",values_to ="Value")
# Merging the above data with HUC06 shapefile by "Name". This is done to geospatially connect the "dfdata_short" with "huc6_shp"
data_merged <- merge(huc6_shp,dfdata_short,by='Name')
# Final Plot
ggfilename <- paste(output_dir,"HUC06_SpatialMaps_HSS_ENSMEAN_Fall_Fertilization_PNW_NDJF.jpeg",sep = "") # output figure's name
plot1 <- ggplot() + geom_sf(data = data_merged, aes(fill = Value)) +
scale_fill_gradientn(colours=c("orangered4","brown4","chocolate","yellow","white","green","darkgreen","darkblue","darkviolet"),
n.breaks=10,limits = c(-100,100), name='Heidke Skill Score') +
facet_grid(Group ~ Init,switch="y",labeller=label_wrap_gen(11))+ scale_x_continuous(breaks = seq(-125, -109, by = 3))+
scale_y_continuous(breaks = seq(40, 54, by = 2),position='left')+
geom_sf(data = huc6_shp, mapping = aes(fill = OBJECTID), color = alpha("black",0.5),size = 0.5, fill = NA) +
ylab("Seasons") + theme_bw() +
theme(strip.placement = 'outside',panel.spacing.x = unit(0.2,"cm"), axis.text=element_text(size=11,face="bold"),
axis.text.x=element_text(angle=90,size=11,face="bold"),axis.title.x = element_blank(), axis.title.y =element_blank(),
panel.grid.major = element_blank(),panel.grid.minor = element_blank(), legend.title = element_text(angle =0,size=11,face='bold'),
legend.text = element_text(size=13),legend.position="bottom",legend.title.align = 0.5,
strip.text = element_text(size=13,face="bold"))+
guides(reverse = TRUE,fill =guide_colourbar(barwidth =35, barheight =1,title.position = "bottom"))+
jpeg(filename=ggfilename, bg="white", width=7000, height=3500, pointsize=15, res=600, quality=100)
plot(plot1)
dev.off()
rm(dfdata,data_merged)
```
#-------------------------------------------------------------------------------
## BAR PLOT - HSS FALL FERTILIZATION (Figure 4)
#-------------------------------------------------------------------------------
```{r HSS Vegetation}
# Reading vegetation file
vegetation_file <- paste(input_dir,"PNW_crop_coverage_with_area_2024.txt",sep="")
vegetation <- read_csv(file=vegetation_file,col_names = TRUE, show_col_types = FALSE,
col_select = c("Cell_id","Crop_Code","Crop_Frac","Grid_area_km2","Crop_area_km2"))
colnames(vegetation) <- c("cell_id","Crop_Code","Crop_Frac","Grid_area_km2","Crop_area_km2")
# Extract irrigated and non-irrigated cropland separately
veg_irrg <- filter(vegetation,(Crop_Code >= 100 & Crop_Code <10000))
veg_nonirrg <- filter(vegetation,(Crop_Code >= 10000))
# Removing previous runs data/variable
if (exists('dfdata_bin') == TRUE){
rm(dfdata_bin)
}
# Running code for forecast initialized in November (11), October (10), September (9) and August (8)
for (init in c(11,10,9,8)){
# Path to Heidke skill output file which will be used as input for this code chunk
HSS_inputfilename <- paste(input_dir, "GridWise_Tercile_HeidkeSkillScore_Fall_Fertilization_InitMonth_0",init,"_PNW_BothThreshold_NDJF.txt",sep="")
# Check if file exists in the input directory or not
if (file.exists(HSS_inputfilename) == FALSE){
text0 <- paste("File Does not Exist !",HSS_inputfilename)
print(text0)
}else{
# Reading input file and removing NA's if any
HSS_data0 <- read_csv(file = HSS_inputfilename, col_names = TRUE, show_col_types = FALSE)
colnames(HSS_data0) <- c("Lat","Lon","Below_33rd_Percentile","Between","Above_67th_Percentile")
HSS_data0 <- na.omit(HSS_data0)
# Merge Elevation data to attach "cell_id" to HSS data based on "Lat" and "Lon"
HSS_data1 <- merge(HSS_data0,elevation,by=c("Lat","Lon"))
#STEP1: Extract Only Irrigated Grid Cells
HSS_data2 <- merge(HSS_data1,veg_irrg,by="cell_id",all.x=TRUE)
HSS_data2 <- na.omit(HSS_data2)
HSS_data2['Category'] <- as.factor("Irrigated") # Make a new column named "Category" and fill it up with management type i.e. "Irrigated"
#STEP2: Generate weighted mean HSS (multiply irrigated crop_area of individual grids to HSS and then divide it with total area of irrigated grids)
HSS_data2['B33'] <- HSS_data2$Below_33rd_Percentile * HSS_data2$Crop_area_km2 # For Below 33rd percentile category
HSS_data2['A67'] <- HSS_data2$Above_67th_Percentile * HSS_data2$Crop_area_km2 # For Above 67th percentile category
HSS_data3 <- HSS_data2 %>% group_by(Category) %>%
summarize("Forecast of Cold Winters" = sum(B33)/sum(Crop_area_km2),"Forecast of Warm Winters" = sum(A67)/sum(Crop_area_km2))
## Repeat above steps (STEP1 & STEP2) for non-irrigated cropgrids
# Extract Only Non-Irrigated Grid Cells
HSS_data4 <- merge(HSS_data1,veg_nonirrg,by="cell_id",all.x=TRUE)
HSS_data4 <- na.omit(HSS_data4)
HSS_data4['Category'] <- as.factor("Non Irrigated") # Make a column named "Category" --> as.factor(Non-Irrigated)
#Generate weighted mean HSS (multiply non-irrigated crop_area of individual grids to HSS and then divide it with total area of Non-irrigated grids)
HSS_data4['B33'] <- HSS_data4$Below_33rd_Percentile * HSS_data4$Crop_area_km2
HSS_data4['A67'] <- HSS_data4$Above_67th_Percentile * HSS_data4$Crop_area_km2
HSS_data5 <- HSS_data4 %>% group_by(Category) %>%
summarize("Forecast of Cold Winters" = sum(B33)/sum(Crop_area_km2), "Forecast of Warm Winters" = sum(A67)/sum(Crop_area_km2))
# Join above data frames (Irrigated and Non-irrigated) row-wise i.e. use "rbind"
bin_data <- rbind(HSS_data3,HSS_data5)
rm(HSS_data2,HSS_data4,HSS_data3,HSS_data5)
# Make Column Named "Init" to save Lead month --> converted from initialization month
lookt <- c(0,0,0,0,0,-5,-4,-3,-2,-1,0,0) # Look out table
init1 = lookt[init] # Based on the look out table, initialization month is converted into lead month.
bin_data['Init'] <- factor(init1)
# Creating new variable to append HSS data for all initialization together
if (exists('dfdata_bin') != TRUE){ # if 'dfdata_bin' doesn't exist, create this variable and save the above data in it.
dfdata_bin <- bin_data
rm(bin_data)
}else{ # if 'dfdata_bin' already exist, append the data from other intializations to it.
dfdata_bin <- rbind(dfdata_bin,bin_data) # This is the reason, we ensured that 'dfdata_bin' shouldn't exists (if exists for any reason, remove it) at the beginning of this code chunk.
rm(bin_data)
}
}
}
# Removing any NA's
dfdata_bin <- na.omit(dfdata_bin)
dfdata_bin$Init <- factor(dfdata_bin$Init, levels = c(0,-1,-2,-3)) # Factoring the lead months and ordering them for plotting purposes
dfdata_bin$Category <- factor(dfdata_bin$Category,levels=c("Irrigated","Non Irrigated")) # Factoring the "category" column and ordering it for plotting purposes
# Format the data in long format for easy plotting using "facet_grid"
dfdata_short <- dfdata_bin %>% pivot_longer(!c("Category","Init"),names_to="Threshold",values_to ="HSS")
# Final Plot
ggfilename <- paste(output_dir,"Fall_Fertilization_HSS_VEGETATION_Correlation_BINNED_Bargraph_NDJF.jpeg",sep = "") # output figure's name
plot1 <- ggplot(data = dfdata_short, aes(x= str_wrap(Category,width=9), y= HSS,fill = Category))+
geom_bar(stat="identity",width=0.5,color=c("darkblue"))+scale_fill_manual(values=c("blue","darkgreen"))+
facet_grid(Threshold ~ Init,switch="y",labeller=label_wrap_gen(11))+
xlab("Category") + ylab("Initializaiton") + theme_bw() +
theme(strip.placement = 'outside',panel.spacing.x = unit(0.2,"cm"), axis.text=element_text(size=11,face="bold"),
axis.text.x=element_text(angle=0,size=8,face="bold"), axis.title.x = element_blank(), axis.title.y =element_blank(),
panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
legend.title = element_text(angle =270,size=18,face='bold'),
legend.text = element_text(size=18),legend.title.align = 0.5,strip.text = element_text(size=18,face="bold"))+
guides(reverse = TRUE,fill =guide_colourbar(barwidth = 1, barheight = 20,title.position = "right"))+
jpeg(filename=ggfilename, bg="white", width=2500, height=1500, pointsize=13, res=300, quality=100)
plot(plot1)
dev.off()
rm(plot1, dfdata_bin,dfdat_short)
```
#-------------------------------------------------------------------------------
## Forecast Skill in Predicting Drought Based on the Regional Water Supply (Figure 5)
#-------------------------------------------------------------------------------
```{r Drought Response, echo=FALSE, warning = FALSE}
# Removing previous runs data/variable
if (exists('dfdata') == TRUE){
rm(dfdata)
}
# Running code for forecast initialized in April, March, February and January
for (init in c(4,3,2,1)){
# Path to Heidke skill output file
HSS_inputfilename <- paste(input_dir,"HUC06_HeidkeSkillScore_Accumulated_Baseflow_Runoff_InitMonth_0",
init,"_PNW_AMJJAS_75percentMedian_BothThreshold.txt",sep="")
# Check if file exists in the input directory or not
if (file.exists(HSS_inputfilename) == FALSE){
text0 <- paste("File Does not Exist !",HSS_inputfilename)
print(text0)
}else{
# Reading input file and removing NA's if any
HSS_data <- read_csv(file = HSS_inputfilename,col_names = TRUE, show_col_types = FALSE,col_select = c("Name","BinaryForecast_75percentMedian"))
HSS_data <- na.omit(HSS_data)
# Converting Initialization Month into Lead-Month
lookt <- c(-3,-2,-1,0,0,0,0,0,0,-6,-5,-4) # Look out table
init1 = lookt[init] # Based on the look out table, initialization month is converted into lead month.
HSS_data['Init'] <- factor(init1)
# Creating new variable to append HSS data for all initialization together
if (exists('dfdata') != TRUE){ # if 'dfdata' doesn't exist, create this variable and save the HSS file's data in it.
dfdata <- HSS_data
rm(HSS_data)
}else{ # if 'dfdata' already exist, append the HSS file's data from other intializations to it.
dfdata <- rbind(dfdata,HSS_data) # This is the reason, we ensured that 'dfdata' shouldn't exists (if exists for any reason, remove it) at the beginning of this code chunk.
rm(HSS_data)
}
}
}
dfdata$Init <- factor(dfdata$Init, levels = c(0,-1,-2,-3)) # Factoring the lead months and ordering them for plotting purposes
# Merging the above data with HUC06 shapefile by "Name". This is done to geospatially connect the "dfdata_short" with "huc6_shp"
data_merged <- merge(huc6_shp,dfdata,by='Name')
# Final Plot
ggfilename <- paste(output_dir,"HUC06_SpatialMaps_HSS_DroughtResponse_AMJJAS.jpeg",sep = "") # output figure's name
plot1 <- ggplot() + geom_sf(data = data_merged, aes(fill = BinaryForecast_75percentMedian)) +
scale_fill_gradientn(colours=c("orangered4","brown4","chocolate","yellow","white","green","darkgreen","darkblue","darkviolet"),
n.breaks=10,limits = c(-100,100), name='Heidke Skill Score') +
facet_grid(~ Init,switch="y",labeller=label_wrap_gen(11))+ scale_x_continuous(breaks = seq(-125, -109, by = 3))+
scale_y_continuous(breaks = seq(40, 54, by = 2),position='left')+
geom_sf(data = huc6_shp, mapping = aes(fill = OBJECTID), color = alpha("black",0.5),size = 0.5, fill = NA) +
ylab("Seasons") + theme_bw() +
theme(strip.placement = 'outside',panel.spacing.x = unit(0.2,"cm"), axis.text=element_text(size=11,face="bold"),
axis.text.x=element_text(angle=90,size=11,face="bold"),axis.title.x = element_blank(), axis.title.y =element_blank(),
panel.grid.major = element_blank(),panel.grid.minor = element_blank(), legend.title = element_text(angle =0,size=11,face='bold'),
legend.text = element_text(size=13),legend.position="bottom",legend.title.align = 0.5,
strip.text = element_text(size=13,face="bold"))+
guides(reverse = TRUE,fill =guide_colourbar(barwidth =35, barheight =1,title.position = "bottom"))+
jpeg(filename=ggfilename, bg="white", width=7000, height=3500, pointsize=15, res=600, quality=100)
plot(plot1)
dev.off()
rm(dfdata,data_merged,plot1)
```
#-------------------------------------------------------------------------------
## Forecast Skill in Drought Response - Yakima Basin (Figure 6)
#-------------------------------------------------------------------------------
## Spatial Maps of Drought Response of Others Basins - Lead 0 - HSS, Elevation, Actual runoff+baseflow
```{r Gridwise Binary Drought Response Spatial Maps - Others, echo=FALSE, warning = FALSE}
#-------------------------------------------------------------------------------
## FUNCTION FOR SPATIAL OPERATIONS
#-------------------------------------------------------------------------------
perform_spatial_operations <- function(current_huc_name, full_huc_shapefile, data_transformed_as_sf) {
nam1 <- subset(full_huc_shapefile, Name == current_huc_name) # Subset the HUC06 file to extract current sub-basin's shapefile.
shp1 = st_transform(structure(nam1, proj4string = "+init=epsg:3857"), "+init=epsg:4326") # Transform the projection of subsetted sub-basin's shapefile
intersect_ind =st_intersects(data_transformed_as_sf, shp1, sparse=FALSE) # Finding row index of coordinates in sf_data (i.e. merged_data) which falls within sub-basin.
data_hucc = data_transformed_as_sf[intersect_ind,] # Extracting data from sf_data based on "intersect_ind".
df_data_huc <- st_drop_geometry(data_hucc)
df_data_huc <- na.omit(df_data_huc) # Removing NA's in the data
return(df_data_huc)
}
ggfilename <- paste(output_dir,"YK_SpatialMaps_DroughtResponse_GridWiseHSS_Elevation_ActualRunoffBaseflow_AMJJAS.jpeg",sep = "") # output figure's name
# Reading Input file of Grid level HSS --> Binary forecast of Drought or non-drought
HSS_inputfilename <- paste(input_dir, "GridWise_BinaryThreshold_HeidkeSkillScore_Drought_Response_InitMonth_04_PNW_75percentMedian_BothThreshold.txt",sep="")
HSS_data <- read_csv(file = HSS_inputfilename,col_names = TRUE, show_col_types = FALSE)
HSS_data <- na.omit(HSS_data) # Removing NA's if any
# Merge Elevation data to HSS data based on "Lat" and "Lon"
elevation1 <- merge(HSS_data,elevation, by=c("Lat","Lon"))
elevation1$Lat1 <- elevation1$Lat # Duplicating Latitudes in a new variable "Lat1". This is done to ensure Latitude information in a later steps.
elevation1$Lon1 <- elevation1$Lon # Duplicating Longitudes in a new variable "Lon1". This is done to ensure Longitude information in a later steps.
# Transforming merged data into a shapefile for subsequent processing.
sf_data = st_as_sf(elevation1, coords = c("Lon", "Lat"),crs=4326) # During this step, "Lat" and "Lon" becomes inaccessible. This is why we have duplicated them in earlier steps.
# Extracting data for Yakima Basin only
name_huc <- huc6_shp$Name # Name of all the basins at HUC06 levels
current_huc <- name_huc[11] # Current Sub-basin i.e.Yakima. This is hardcoded for Yakima.
df_data_huc <- perform_spatial_operations(current_huc, huc6_shp, sf_data) # Perform spatial operation on current sub-basin and extracting data for Yakima.
# Extracting the geographical extent of Yakima
Lat_min <- round(min(df_data_huc$Lat1))
Lat_max <- round(max(df_data_huc$Lat1))
Lon_min <- round(min(df_data_huc$Lon1))
Lon_max <- round(max(df_data_huc$Lon1))
# Extracting Yakima's shapefile from the PNW's HUC06 shapefile
polygon_to_plot <- huc6_shp[huc6_shp$Name == current_huc, ]
polygon_to_plot <- st_transform(polygon_to_plot,crs=4326)
mapRange1 <- st_bbox(polygon_to_plot)
# Plotting HSS for Yakima River Basin at Lead 0 i.e. HSS for April intialized forecast
plot1 <- ggplot()+ geom_tile(data = df_data_huc, aes(x = Lon1, y = Lat1, fill = HeidkeSkillScore_DroughtVsNonDrought)) +
scale_fill_gradientn(colours=c("orangered4","brown4","chocolate","darkorange","grey50","darkgreen","cyan","darkblue","darkviolet"),
n.breaks=10,limits = c(-100,100), name='Heidke Skill Score')+
scale_x_continuous(breaks = seq(Lon_min,Lon_max, by = 1))+ scale_y_continuous(breaks = seq(Lat_min,Lat_max, by = 0.5),position='left')+
geom_sf(data = polygon_to_plot, mapping = aes(fill = OBJECTID), color = alpha("black",0.5),size = 0.5, fill = NA) +
coord_sf(xlim = mapRange1[c(1,3)], ylim = mapRange1[c(2,4)])+
theme_bw() + theme(strip.placement = 'outside',panel.spacing.x = unit(0.2,"cm"), axis.text=element_text(size=13,face="bold"),
axis.text.x=element_text(angle=0,size=13,face="bold"),axis.title.x = element_blank(), axis.title.y =element_blank(),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position="bottom",
legend.title = element_text(angle =0,size=13,face='bold'), legend.text = element_text(size=13),
legend.title.align = 0.5,strip.text = element_text(size=13,face="bold"))+
guides(reverse = TRUE,fill =guide_colourbar(barwidth = 18, barheight = 1,title.position = "bottom"))
# Plotting Elevation map of Yakima
plot2 <- ggplot()+geom_tile(data = df_data_huc, aes(x = Lon1, y = Lat1, fill = Elevation)) +
scale_fill_gradientn(colours=c("lightskyblue","slategray3","lemonchiffon","salmon1","tomato1","tomato4"),
n.breaks=6,breaks = c(1,500,1000,1500,2000,2500,3300),name='Elevation')+
scale_x_continuous(breaks = seq(Lon_min,Lon_max, by = 1))+ scale_y_continuous(breaks = seq(Lat_min,Lat_max, by = 0.5),position='left')+
geom_sf(data = polygon_to_plot, mapping = aes(fill = OBJECTID), color = alpha("black",0.5),size = 0.5, fill = NA) +
coord_sf(xlim = mapRange1[c(1,3)], ylim = mapRange1[c(2,4)])+
theme_bw() + theme(strip.placement = 'outside',panel.spacing.x = unit(0.2,"cm"), axis.text=element_text(size=13,face="bold"),
axis.text.x=element_text(angle=0,size=13,face="bold"),axis.title.x = element_blank(), axis.title.y =element_blank(),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position="bottom",
legend.title = element_text(angle =0,size=13,face='bold'), legend.text = element_text(size=13),
legend.title.align = 0.5,strip.text = element_text(size=13,face="bold"))+
guides(reverse = TRUE,fill =guide_colourbar(barwidth = 18, barheight = 1,title.position = "bottom"))
# Arrange the HSS and Elevation map row-wise and saving it
plot4 <- egg::ggarrange(plot1,plot2, nrow=1)
ggsave(filename = ggfilename,plot=plot4,height=5,width=12,units="in",dpi=1200)
rm(plot4,plot1,plot2,df_data_huc)
```