-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWQdash_public.Rmd
5715 lines (4739 loc) · 280 KB
/
WQdash_public.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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Water in Our Parks"
output:
flexdashboard::flex_dashboard:
theme: yeti # theme options: default, cosmo, bootstrap, cerulean, journal, flatly, readable, spacelab, united, lumen, paper, sandstone, simplex, yeti
orientation: columns
vertical_layout: fill
horizontal_layout: fill
runtime: shiny
---
```{r global, include=FALSE}
### UPCOMING CHANGES:
# > rnoaa is not available for R3.2. This package is going to be phased out in 2024, so keep an eye out
# https://waterdata.usgs.gov/blog/wqx3/
# A large update of dataRetrieval was just pushed to GitHub. This update will allow users to access the new "WQX3" profiles from the Water Quality Portal. Any new USGS discrete water quality data since March 11th is ONLY available via dataRetrieval from these new data profiles. With this update, all WQP functions that can use these new profiles will use them by default.
#
# I'd encourage anyone who uses dataRetrieval for discrete water quality data to install this new update and give it a good test. If you would be willing to test out the updates, use the "remotes" package to install dataRetrieval:
#
# remotes::install_github("DOI-USGS/dataRetrieval")
#
# You'll need to update scripts downstream of the WQP pulls to new column names and possibly different values returned. Eventually, you'll HAVE to update your workflows (the legacy profiles will eventually be retired). If you need to switch back to the production version of dataRetrieval, you can re-install (after unloading the package) by reinstalling the CRAN version:
#
# install.packages("dataRetrieval")
#
# Please submit any bugs/questions/issues here:
# https://github.com/DOI-USGS/dataRetrieval/issues
#
# Or email: CompTools@usgs.gov
#
# I will be on leave from June 17 - July 8, so it would be better to report issues and ask questions via the GitHub issues.
#
# More information is here:
# https://water.code-pages.usgs.gov/dataRetrieval/articles/qwdata_changes.html
# https://water.code-pages.usgs.gov/dataRetrieval/articles/Status.html
# like 4
# Issues · DOI-USGS/dataRetrieval
# This R package is designed to obtain USGS or EPA water quality sample data, streamflow data, and metadata directly from web services. - Issues · DOI-USGS/dataRetrieval
# Install and load packages
rm(list=ls())
pkgs <- c("flexdashboard",
"shiny",
"knitr",
"here",
"plyr",
"tidyverse",
"janitor",
"mgcv",
"scales",
"rlang", # check for empty variables <<<<<<<<<<<<
"rtf",
"rmarkdown",
"shinyWidgets",
"leaflet",
"plotrix",
"GGally",
"plotly",
"httr",
"sp",
"bslib", # for accordion panels
"bsicons",
"RgoogleMaps", # to set map zoom
"sf",
"magrittr",
"leaflet.extras",
"lubridate",
"fontawesome",
"viridisLite",
"ggpubr", # for drawing separate legends
"heatmaply", # for interactive heat plots
"reactable", # for easy nested tables
"htmltools", # for arranging plots in tab (browsable)
"shinyFiles", # for user to save files in specified location
"RColorBrewer", # to display brewer palettes
"shinyjs", # for easy functions that use JavaScript
"sortable", # drag-and-drop rank input
"tmaptools", # for flexible color mapping (get_brewer_pal)
"DT", # for interactive tables
"zoo", # for year-month
"cowplot", # to get legends from plots
"gridExtra", # for arranging plots and adding plot annotations (ggplotly can't do captions or subtitles)
"RgoogleMaps", # for MaxZoom & MinZoom
"geojsonio", # to test for presence of features
"lemon", # for facet_rep_wrap
# "EnvironmentalSettingToolkit", # installed from github
# "rnoaa", # to get NOAA climate data <<<<< THIS PACKAGE WILL RETIRE SOON. KEEP AN EYE ON THIS.
"leaflet.minicharts") # for web etiquette with APIs
installed_pkgs <- pkgs %in% installed.packages()
if (length(pkgs[!installed_pkgs]) > 0) install.packages(pkgs[!installed_pkgs], repos = "https://cloud.r-project.org", dep=TRUE)
invisible(lapply(pkgs, library, character.only = TRUE))
# Check for required dashboard files
req_files <- c("park_noaa_overlaps_list.RDS", "park_gage_overlaps_list.RDS", "parks_sf.RDS", "unique_parks_df.csv")
have_files <- list.files(path = here::here("dashboard_files"))
try(if(!all(req_files %in% have_files)) stop(paste("Missing required dashboard files in 'dashboard_files' subfolder:", setdiff(req_files, have_files))))
# Read in park choice file
unique_parks_df <- read_csv("dashboard_files/unique_parks_df.csv")
options(shiny.maxRequestSize = 20*1024^2,
timeout = 1500,
stringsAsFactors = FALSE,
dplyr.summarise.inform = FALSE
)
```
```{r css}
# Force modal to fill width of screen
# tags$style("#plot_tab .modal-dialog .modal-content .modal-body {
# inline-size: 95%;
# font-size: 12px;
# max-width: 100%;
# margins: 0;
# padding: 0;
# width: 2000px;
# height: calc(100vh - 80px) !important;
# }")
# This forces datatable to fill height of modal
tags$style(".dataTables_scrollBody {
height: calc(100vh - 180px) !important;
}")
# This sizes and positions the custom gif loading images
tags$style("dropdown-toggle {
background-color:lightblue !important;
padding:6px;
}")
tags$style("#gif_modal .modal-body {padding:0px}
#gif_modal .modal-dialog {width:auto; display:inline-block; position:absolute; top:35%;left:50%; transform:translate(-50%, -50%) !important;}
")
# This expands initial map to fill screen
tags$style("map {
height: calc(100vh - 80px) !important;
}")
# Call this to force an input value to reset to NULL
tags$script("
Shiny.addCustomMessageHandler('setNull', function(variableName) {
Shiny.setInputValue(id = variableName, value = null);
});
")
# Call this to force an input value to reset to a specified value
tags$script("
Shiny.addCustomMessageHandler('resetValue', function(variableName, inputValue) {
Shiny.setInputValue(id = variableName, value = inputValue);
});
")
# When an action button is disabled, text should be gray and button color light gray
tags$style(".btn.disabled {
color:gray;
background-color:light-gray;
}")
tags$style(".rank-list-title {
font-size:14px;
padding:4px;
}")
tags$style(".rank-list-item {
font-size:14px;
padding:4px;
}")
tags$style("table.dataTable tbody th, table.dataTable tbody td input.form-control {
padding: 2px 5px;
}") # reduce padding in data tables
tags$style(HTML(".shiny-output-error-validation {
font-size:14px;
color: #FF0000;
}")
) # validation text is in red. Could also add 'font-weight: bold;'
tags$style(".reactable {
font-size: 13px;
}") # font size for reactable tables
tag.map.title <- tags$style(HTML("
.leaflet-control.map-title {
text-align: center;
font-weight: bold;
background: rgba(255,255,255,0.75); # white box
font-size: 28px;
color: darkred;
}
")) # add title to leaflet map
tags$style(".map-unitcode {
font-weight: bold;
background: rgba(255,255,255,0.75); # white box
font-size:28px;
}") # add bold park unit name/code to leaflet map
tags$style(".chart-stage-flex {
overflow: scroll !important;
}") # Helps ensure data table bottoms don't get cut off
```
```{r generic_action_buttons}
# Action to cancel modal
observeEvent(eventExpr = input$button_cancelModal, {
removeModal()
})
```
```{r functions}
### FUNCTIONS ----
# Web etiquette
# polite_GET <- politely(httr::GET, verbose=TRUE)
FuncAboutButton <- function(nam) {
actionButton(nam, " PAGE INSTRUCTIONS", icon = icon("question-sign", lib = "glyphicon"), width = "100%")
}
FuncShowWellPanel <- function(input_to_test, wp_to_toggle) {
# Function to show or hide a well panel based on a checkbox selection
#
# Args:
# input_to_test: The ID of the checkbox input, e.g., input$sel_ShowPanel
# wp_to_toggle: ID of the well panel to toggle, e.g., wp_example
#
shiny::req(!is.null(rv$dat),!is.null(input_to_test))
if(input_to_test) {
shinyjs::showElement(wp_to_toggle)
} else {
shinyjs::hideElement(wp_to_toggle)
}
}
FuncAllNoneButtons <- function(cond, name_all, name_none) {
# Function to create 'Select All' and 'Select None' action buttons
#
# Args:
# cond: The input ID that needs to be defined for buttons to show (enter as input.XXX rather than as input$XXX)
# name_all: ID to assign to 'Select All' button
# name_none: ID to assign to 'Select None' button
#
conditionalPanel(
condition = paste0("typeof ", cond, " !== 'undefined'"),
actionButton(name_all, "Select All", style="color:black; display:inline-block; border:1px; padding:4px 12px;"),
actionButton(name_none, "Select None", style="color:black; display:inline-block; border:1px; padding:4px 12px;")
)
}
FuncCalcWaterSeasons <- function(dateVec){
# Function to calculate water year from calendar date (modified from calcWaterSeasons function in package 'dataRetrieval')
# POSIXlt years start at 100, POSIXlt months start at 0
dateTimeVec <- as.POSIXlt(dateVec)
calYear <- dateTimeVec$year + 1900
calMon <- dateTimeVec$mon + 1
# when the date is NA, it should not try to add 1
whichPastOct <- calMon >= 10
whichPastOct[is.na(whichPastOct)] <- FALSE
# add one to the year if it is in October or after
WaterSeasons <- calYear
WaterSeasons[whichPastOct] <- calYear[whichPastOct] + 1
return(WaterSeasons)
}
FuncBreakDates <- function(dat_df) {
# Function to break dates into date categories
#
# Args:
# dat_df: A data frame with the raw data. One column needs to be ActivityStartDate, which is date class with format yyyy-mm-dd
#
dat_df2 <- dat_df %>%
dplyr::mutate(
YrDate = base::as.Date(cut(ActivityStartDate, breaks = "year")), # these maintain date class, so are useful for certain summaries
MnthDate = base::as.Date(cut(ActivityStartDate, breaks = "month")),
WkDate = base::as.Date(cut(ActivityStartDate, breaks = "week", start.on.monday = FALSE)), # Sunday start of week
MeteoYr = as.integer(lubridate::year(ActivityStartDate)), # for other types of summaries
WaterYr = as.integer(FuncCalcWaterSeasons(ActivityStartDate)),
Season = factor(cut(lubridate::yday(ActivityStartDate),
breaks=c(-Inf, 59, 151, 243, 334, Inf),
labels=c("Winter","Spring","Summer", "Fall", "Winter")), levels = c("Spring","Summer", "Fall", "Winter")), # Meteorological Seasons: Spring=March 1 - May 31; Summer=June 1 - Aug 31; Fall=Sept1 - Nov30; Winter=Dec1 - Feb28
Mnth = lubridate::month(ActivityStartDate, label = TRUE, abbr = TRUE),
Wk = factor(lubridate::week(ActivityStartDate), levels = 1:52),
DayOfYr = lubridate::yday(ActivityStartDate))
dat_df2$Mnth = factor(dat_df2$Mnth, levels = levels(dat_df2$Mnth), ordered = FALSE)
return(dat_df2)
}
FuncOrderCheck <- function(import = FALSE, filter_internal = FALSE, filter_external = FALSE, plot = FALSE) {
# Function to check if data have been imported, filtered, and plot data summarized
if(import) {
shiny::validate(
need(!is.null(rv$dat), message = "No data available. Please use the 'Get WQP Data' tab to first import or load water quality data."))}
if(filter_internal) {
shiny::validate(
need(!is.null(rv_param_temp$subDat) & !is.null(rv_param_temp$subDatTypes), message = "From the left sidebar, choose a subset of data to work with"))}
if(filter_external) {
shiny::validate(
need(!is.null(rv_param_temp$subDat) & !is.null(rv_param_temp$subDatTypes), message = "On the 'Define & Filter Data' page, please choose a subset of data to work with"))}
if(plot) {
shiny::validate(
need(!is.null(rv_param_temp$plotDat), message = "On the 'Explore Data' page, select characteristic(s) and monitoring site(s) to plot and then click the green 'REFRESH PLOT DATA' button."))
}
}
FuncCustomSeasons <- function(dat_df, seas) {
# Function to assign USGS water year or custom seasons to ActivityStartDate
#
# Args:
# dat_df: A data frame to modify. One column needs to be ActivityStartDate, which is date class with format yyyy-mm-dd
# seas: character string, "WaterSeasons" or "CustomSeasons"
#
dat_df$Season <- NA
# assign the custom season names based on dates. Can't just use cut, in case the seasons aren't consecutive
if(seas == "WaterSeasons") {
df_CustomSeason <- data.frame(
Name = c("Fall(WY)", "Winter(WY)", "Spring(WY)", "Summer(WY)"),
RangeStart = as.Date("2018-01-01")-1 + c(274, 1, 91, 182),
RangeEnd = as.Date("2018-01-01")-1 + c(265, 90, 181, 273))
}
if(seas == "CustomSeasons") {
df_CustomSeason <- data.frame(
Name = c(input$sel_Season1Name, input$sel_Season2Name, input$sel_Season3Name, input$sel_Season4Name),
RangeStart = c(input$sel_Season1Range[1], input$sel_Season2Range[1], input$sel_Season3Range[1], input$sel_Season4Range[1]),
RangeEnd = c(input$sel_Season1Range[2], input$sel_Season2Range[2], input$sel_Season3Range[2], input$sel_Season4Range[2]))
}
df_CustomSeason <- df_CustomSeason[df_CustomSeason$Name != "",] # if no name assigned, then it's not a season level
for(i in 1:nrow(df_CustomSeason)) {
Name <- df_CustomSeason$Name[i]
StartDate <- lubridate::yday(df_CustomSeason$RangeStart[i])
StartDate_LY <- lubridate::yday(gsub("^.{1,4}", "2000", df_CustomSeason$RangeStart[i])) # yday count is different for leap years
EndDate <- lubridate::yday(df_CustomSeason$RangeEnd[i])
EndDate_LY <- lubridate::yday(gsub("^.{1,4}", "2000", df_CustomSeason$RangeEnd[i])) # yday count is different for leap years
if(StartDate < EndDate) {
# for leap year
dat_df$Season[lubridate::leap_year(dat_df$ActivityStartDate) & lubridate::yday(dat_df$ActivityStartDate) >= StartDate_LY & lubridate::yday(dat_df$ActivityStartDate) <= EndDate_LY] <- Name
# for not leap year
dat_df$Season[!lubridate::leap_year(dat_df$ActivityStartDate) & lubridate::yday(dat_df$ActivityStartDate) >= StartDate & lubridate::yday(dat_df$ActivityStartDate) <= EndDate] <- Name
} else { # start yday is larger than end yday, it means it spans Dec 31-Jan 1
# for leap year
dat_df$Season[lubridate::leap_year(dat_df$ActivityStartDate) & lubridate::yday(dat_df$ActivityStartDate) >= StartDate_LY] <- Name
dat_df$Season[lubridate::leap_year(dat_df$ActivityStartDate) & lubridate::yday(dat_df$ActivityStartDate) <= EndDate_LY] <- Name
# for not leap year
dat_df$Season[!lubridate::leap_year(dat_df$ActivityStartDate) & lubridate::yday(dat_df$ActivityStartDate) >= StartDate] <- Name
dat_df$Season[!lubridate::leap_year(dat_df$ActivityStartDate) & lubridate::yday(dat_df$ActivityStartDate) <= EndDate] <- Name
}
}
dat_df$Season <- factor(dat_df$Season, levels = df_CustomSeason$Name)
return(dat_df)
}
FuncBaseMap <- function(maptype) {
cbp1 <- c("#E69F00", "#56B4E9", "#009E73", "#CC79A7", "#0072B2", "#D55E00", "#999999", "#F0E442", "#000000", "chocolate4", "purple4", "chartreuse", "lightpink", "honeydew2") # Colorblind-friendly palette
print("in FuncBaseMap")
cbp1_org <- switch((length(unique(rv$sitesPointsSub$OrganizationFormalName)) <= length(cbp1)) + 1, colorRampPalette(cbp1)(length(unique(rv$sitesPointsSub$OrganizationFormalName))), cbp1[1:length(unique(rv$sitesPointsSub$OrganizationFormalName))])
rv_param_temp$palOrg <- colorFactor(palette = cbp1_org, domain = unique(rv$sitesPointsSub$OrganizationFormalName), levels = unique(rv$sitesPointsSub$OrganizationFormalName))
iconGages = makeAwesomeIcon(
text = fa("water"),
iconColor = "black",
markerColor = "blue")
iconMeteo = makeAwesomeIcon(
icon= "fa-cloud",
library = "fa",
squareMarker = TRUE,
markerColor = "white")
iconCWA = makeAwesomeIcon(
icon= "fa-building",
library = "fa",
markerColor = "lightgray")
iconGagesSelected = makeAwesomeIcon(
text = fa("water"),
iconColor = "black",
markerColor = "orange")
iconMeteoSelected = makeAwesomeIcon(
icon= "fa-cloud",
library = "fa",
squareMarker = TRUE,
markerColor = "orange")
print("Creating base map")
# Order map layers -- higher zIndex is on "top"
map <- leaflet(options = leafletOptions(zoomControl = FALSE, zoomSnap = 0.25)) %>%
addMapPane("pane_unitPoly", zIndex = 210) %>%
addMapPane("pane_HUC", zIndex = 220) %>%
addMapPane("pane_facilitiesPoints", zIndex = 225) %>%
addMapPane("pane_meteoStations", zIndex = 230) %>%
addMapPane("pane_gageStations", zIndex = 235) %>%
addMapPane("pane_meteoStations_selected", zIndex = 240) %>%
addMapPane("pane_gageStations_selected", zIndex = 245) %>%
addMapPane("pane_availableStations", zIndex = 255) %>%
addMapPane("pane_selectedStreamlines", zIndex = 257) %>%
addMapPane("pane_selectedStations", zIndex = 260) %>% # always keep selected monitoring station points on "top" of map layers (highest zIndex)
addMapPane("pane_selectedOrigin", zIndex = 265) %>%
addTiles(options = tileOptions(noWrap = TRUE), group = "Street") %>%
addProviderTiles("Esri.WorldImagery", options = providerTileOptions(noWrap = TRUE), group="Satellite") %>%
addPolygons(data = rv$unitPoly, group = "NPS unit", color = "black", fillColor = "yellow", fillOpacity = 0.8, weight = 1, options = pathOptions(pane = "pane_unitPoly")) %>% # park unit outline
addPolygons(data = rv[[rv$importSettings$sel_HUClevel]], group = rv$importSettings$sel_HUClevel, color = "blue", fillColor = "lightblue", fillOpacity = 0.6, weight = 0.5, layerId = ~HUC, options = pathOptions(pane = "pane_HUC")) %>% # HUC polygons
addScaleBar() %>%
addControl(rv$parkName, position = "topleft", className="map-unitcode") # add 4-letter UNIT code on map)
print("Finished base map")
# Conditional mapping (when data are available)
init_sites <- subset(rv$sitesPointsSub, OrganizationFormalName %in% rv$importSettings$sel_Organization & MonitoringLocationTypeName %in% rv$importSettings$sel_SiteType)
if(maptype == "initial") { # These are specific to the initial map
print("Map type is 'initial'")
if(nrow(init_sites) > 0) { # Available water quality stations
map %<>% addCircleMarkers(data = init_sites, group = "Available monitoring sites", label = ~SITELAB, popup = ~SITEPOP, radius = 4, fillColor = ~rv_param_temp$palOrg(OrganizationFormalName), fillOpacity = 0.8, stroke = TRUE, weight = 1, color = ~rv_param_temp$palOrg(OrganizationFormalName), opacity = 0.7, options = pathOptions(pane = "pane_availableStations"))
} # WQ stations
if(!is.null(rv$selectedStations)) {
sel_stations <- rv$sitesPointsSub %>% dplyr::filter(MonitoringLocationIdentifier %in% rv$selectedStations$MonitoringLocationIdentifier)
if(nrow(sel_stations) > 0) {
print("Mapping selected sites")
map %<>%
addCircleMarkers(data = rv$sitesPointsSub %>% dplyr::filter(MonitoringLocationIdentifier %in% rv$selectedStations$MonitoringLocationIdentifier), group = "Selected monitoring sites", label = ~SITELAB, popup = ~SITEPOP, radius = 8, fillColor = ~rv_param_temp$palOrg(OrganizationFormalName), fillOpacity = 0.8, stroke = TRUE, weight = 4, color = "white", opacity = 1, options = pathOptions(pane = "pane_selectedStations"))
}
}
if(all(!is.null(rv$selectedOriginStation), !is.null(rv$importSettings$sel_SelectMethod))){ # the origin station for up-down selection is outlined in red
if(rv$importSettings$sel_SelectMethod=="methodDist") {
if(nrow(rv$sitesPointsSub[rv$sitesPointsSub$MonitoringLocationIdentifier == rv$selectedOriginStation$identifier,]) > 0) {
map %<>%
addCircleMarkers(data = rv$sitesPointsSub[rv$sitesPointsSub$MonitoringLocationIdentifier == rv$selectedOriginStation$identifier,], group = "Selected monitoring sites", label = ~SITELAB, popup = ~SITEPOP, radius = 8, fillOpacity = 0, stroke = TRUE, weight = 4, color = "red", opacity = 1, options = pathOptions(pane = "pane_selectedOrigin"))}
}
}
}
# These are for any map type
if(all(rv$importSettings$sel_SelectMethod=="methodHuc", !is.null(rv$selectedHucs))) { # layer the selected polygons on map, if selection method is by HUC
print("mapping HUCs")
### >>> ERROR BELOW: Error in writeImpl: Text to be written must be a length-one character vector--THIS OCCURS AFTER HAVING SELECTED POINTS
map %<>%
addPolygons(data = rv[[rv$importSettings$sel_HUClevel]][rv[[rv$importSettings$sel_HUClevel]]$HUC %in% rv$selectedHucs,], group = rv$importSettings$sel_HUClevel, color = "blue", fillColor = "lightblue", fillOpacity = 0.8, weight = 1.5, layerId = ~HUC, options = pathOptions(pane = "pane_HUC"))
}
if(all(!is.null(rv$selectedOriginStation), !is.null(rv$importSettings$sel_SelectMethod))){
if(rv$importSettings$sel_SelectMethod=="methodDist") {
if(!is.null(rv$selectedDownstreamLines)) {
map %<>%
addPolylines(data = rv$selectedDownstreamLines, color = "#660000", weight = 2, opacity = 1, group = "Selected monitoring sites", options = pathOptions(pane = "pane_selectedStreamlines")) # downstream lines in brown
}
if(!is.null(rv$selectedUpstreamLines)) {
map %<>%
addPolylines(data = rv$selectedUpstreamLines, color = "#FFFFFF", weight = 2, opacity = 1, group = "Selected monitoring sites", options = pathOptions(pane = "pane_selectedStreamlines")) # upstream lines in blue
}
}
}
print("about to map USGS stations")
if(!is.null(rv$gageStations)) { # Add USGS gage (streamflow) stations only if found
print("map USGS streamflow stations")
map %<>%
addAwesomeMarkers(icon = iconGages, data = rv$gageStations, group = "Gage stations", label = ~GAGELAB, popup = ~GAGEPOP, options = pathOptions(pane = "pane_gageStations")) # selected stream gage stations
}
print("about to map meteoStations")
if(!is.null(rv$meteoStations)) { # Add weather stations only if found
print("map metioStations")
map %<>%
addAwesomeMarkers(icon = iconMeteo, data = rv$meteoStations, group = "Weather stations", label = ~METEOLAB, popup = ~METEOPOP, options = pathOptions(pane = "pane_meteoStations")) # weather stations
}
if(!is.null(rv$facilitiesPointsSub)) { # Add EPA-monitored discharge facilities only if found
print("map EPA facilities")
map %<>%
addAwesomeMarkers(icon = iconCWA, data = rv$facilitiesPointsSub, group = "Discharge facilities", label = ~FACLAB, popup = ~FACPOP)
}
print("about to map selected USGS stations")
if(all(!is.null(rv$gageStations), !is.null(rv$selectedGages))) { # Add selected USGS gage stations only if found
if(all(rv$selectedGages$GageID %in% rv$gageStations$GageID)) {
print("map selected USGS stations")
map %<>%
addAwesomeMarkers(icon = iconGagesSelected, data = rv$selectedGages, group = "Gage stations", label = ~GAGELAB, popup = ~GAGEPOP, options = pathOptions(pane = "pane_gageStations_selected"))
}}
print("about to map selected meteoStations")
if(all(!is.null(rv$meteoStations), !is.null(rv$selectedMeteo))) {
if(all(rv$selectedMeteo$MeteoID %in% rv$meteoStations$MeteoID)) {
print("map selected meteoStations")
map %<>%
addAwesomeMarkers(icon = iconMeteoSelected, data = rv$selectedMeteo, group = "Weather stations", label = ~METEOLAB, popup = ~METEOPOP, options = pathOptions(pane = "pane_meteoStations_selected"))
}}
print("about to return map")
return(map)
}
FuncUpdateHome <- function() {
updateTextInput(session,
"sel_UnitCode",
value = "")
updateSliderInput(session,
"sel_MapZoom",
value = NULL)
updateRadioButtons(session,
"sel_HUClevel",
selected = "HUC10")
updateRadioButtons(session,
"sel_SelectMethod",
selected = "methodHuc")
updateTextInput(session,
"sel_OriginStationID",
value = "")
updateCheckboxGroupInput(session,
"sel_Organization",
choices = NULL,
selected = character(0))
updateCheckboxGroupInput(session,
"sel_Gages",
choices = NULL,
selected = character(0))
updateCheckboxGroupInput(session,
"sel_Meteo",
choices = NULL,
selected = character(0))
# # Reset map center and map bounds to NULL
session$sendCustomMessage(type = "setNull", message = "map_center")
session$sendCustomMessage(type = "setNull", message = "map_bounds")
}
FuncUpdateFilterInputs <- function() {
updateRadioButtons(session,
"sel_DefineSeasons",
selected = rv_param_temp$defaultInputs$sel_DefineSeasons)
updateSliderInput(session,
"sel_SeasonsStart",
value = as.Date("2018-01-01"))
updateTextInput(session,
"sel_Season1Name",
value = "")
updateTextInput(session,
"sel_Season2Name",
value = "")
updateTextInput(session,
"sel_Season3Name",
value = "")
updateTextInput(session,
"sel_Season4Name",
value = "")
updateSliderInput(session,
"sel_YrRange",
min = NULL,
max = NULL,
step = NULL,
value = rv_param_temp$defaultInputs$sel_YrRange)
updateNumericInput(session,
"sel_MinYrs",
value = rv_param_temp$defaultInputs$sel_MinYrs)
updateCheckboxGroupInput(session,
"sel_ActivityType",
selected = rv_param_temp$defaultInputs$sel_ActivityType)
updateCheckboxGroupInput(session,
"sel_ResultStatus",
selected = rv_param_temp$defaultInputs$sel_ResultStatus)
updateCheckboxGroupInput(session,
"sel_SummaryOrg",
selected = rv_param_temp$defaultInputs$sel_SummaryOrg)
}
FuncUpdateInputsOther <- function() {
updateSelectInput(session,
"sel_ShowCharType",
choices = NULL,
selected = NULL)
updateCheckboxGroupInput(session,
"sel_ShowStations",
choices = NULL,
selected = character(0))
updateRadioButtons(session,
"sel_Categ",
choices = "none",
selected = "none")
}
# FuncUpdateTSMap <- function() {
# if(!is.null(rv_param_temp$plotDat)) {
# updateSliderTextInput(session,
# "sel_SurvYr",
# selected = max(rv_param_temp$plotDat$Yr, na.rm = TRUE))
# }
#
# if(!is.null(rv$unitPoly)) {
# updateSliderInput(session,
# "sel_ParamMapZoom",
# selected = min(RgoogleMaps::MaxZoom(lonrange = c(st_bbox(rv$unitPoly)$xmin, st_bbox(rv$unitPoly)$xmax), latrange = c(st_bbox(rv$unitPoly)$ymin, st_bbox(rv$unitPoly)$ymax))) - 1)
# }
# }
# FuncUpdateTSPlots <- function() {
# updateSelectInput(session,
# "sel_ShowThresholds",
# selected = "showthresh_none")
#
# updateSelectInput(session,
# "sel_AddGagePrecip",
# selected = "none")
#
# updateSelectInput(session,
# "sel_YScale",
# selected = "identity")
#
# updateSelectInput(session,
# "sel_Categ",
# selected = "none")
#
# updateSelectInput(session,
# "sel_ParamMapShow",
# selected = "show")
#
# updateCheckboxInput(session,
# "sel_FreeY",
# selected = FALSE)
#
# updateCheckboxInput(session,
# "sel_AddQuantile",
# selected = TRUE)
#
# updateCheckboxInput(session,
# "sel__PlotByStation",
# selected = TRUE)
#
# updateSliderInput(session,
# "sel_MapPointSize",
# selected = 0)
# }
FuncUpdateImportSettings <- function(inputs_to_update) {
shiny::req(!is.null(rv$dat))
input_list <- isolate(reactiveValuesToList(input)) # difficulties indexing reactive list, so convert to unreactive list first
replacement_list <- input_list[inputs_to_update]
names(replacement_list) <- inputs_to_update # adds list element name, even for NULL elements
rv$importSettings <- modifyList(rv$importSettings, replacement_list, keep.null = TRUE) # update only the list elements in replacement_list
}
FuncDataTypes <- function(dat) {
# Function to identify which characteristic names have non-numeric entries, and what those entries are
#
# Args:
# dat: The imported data frame. Requires columns CharacteristicName and ResultMeasureValue
#
# Returns:
# Data frame with each characteristic name, best guess of data type (categorical or numeric), and the non-numeric entries
temp_datatype <- dat %>%
dplyr::select(CharacteristicName, CharSampleType, ResultMeasureValue) %>%
dplyr::group_by(CharacteristicName, CharSampleType)
temp_datatype_count <- temp_datatype %>%
dplyr::summarise(NumRecords = n()) %>%
dplyr::select(CharSampleType, NumRecords)
temp_datatype_categ <- temp_datatype %>%
group_map(~sort(unique(na.omit(.x$ResultMeasureValue[which(is.na(suppressWarnings(as.numeric(gsub(",", "", .x$ResultMeasureValue)))))])))) # identify all non-numeric, non-NA entries for each characteristic. If it's a number with comma, removes the comma and still counts it as a number
df_datatype <- as.data.frame.AsIs(temp_datatype_categ, stringsAsFactors=FALSE) %>% # unfortunately, I can't get the data table edit function to work with factor class variables
dplyr::mutate(CharSampleType = unique(dat$CharSampleType),
DataType = ifelse(temp_datatype_categ %in% c("character(0)", "numeric(0)", "logical(0)"), "numeric", "categorical")) %>%
rowwise() %>%
mutate(NonNumericEntries = paste(temp_datatype_categ, collapse = " // ")) %>% # make sure using unique separator that wouldn't be part of any entry
dplyr::select(-temp_datatype_categ) %>%
dplyr::left_join(temp_datatype_count, by = "CharSampleType") %>%
arrange(DataType, CharacteristicName, CharSampleType)
df_datatype$DataType <- factor(df_datatype$DataType, levels = c("categorical", "numeric")) # only allows these entries
return(df_datatype)
}
FuncFilterSelectCharSampleType <- function(sel_NPSparam, sel_YrRange, sel_SummaryOrg, sel_ActivityType, sel_ResultStatus, sel_MinYrs) {
shiny::req(!is.null(rv$dat))
char_vec <- rv$dat %>%
{if (sel_NPSparam == TRUE & "National Park Service Water Resources Division" %in% rv$dat$OrganizationFormalName) dplyr::filter(., OrganizationFormalName == "National Park Service Water Resources Division") else .} %>%
dplyr::filter(ResultDetectionConditionText != "Not Reported") %>%
dplyr::mutate(Yr = MeteoYr) %>%
dplyr::filter(Yr >= as.integer(sel_YrRange[1]) & Yr <= as.integer(sel_YrRange[2]) & OrganizationFormalName %in% sel_SummaryOrg & ActivityTypeCode %in% sel_ActivityType & ResultStatusIdentifier %in% sel_ResultStatus) %>%
dplyr::select(CharacteristicName, CharSampleType, MonitoringLocationIdentifier, Yr) %>%
dplyr::distinct() %>%
group_by(CharacteristicName, CharSampleType, MonitoringLocationIdentifier) %>%
dplyr::mutate(TotalSurveyYrs = dplyr::n_distinct(Yr)) %>%
dplyr::filter(TotalSurveyYrs >= sel_MinYrs) %>%
dplyr::ungroup() %>%
dplyr::pull(CharSampleType)
return(sort(unique(char_vec)))
}
# FuncHighlightYr <- function(plot_list) {
# h_plot_list <- list()
#
# for(i in 1:length(plot_list)) {
# p <- plot_list[[i]]
#
# highlight_dat <- subset(p$data, Yr == as.integer(input$sel_HighlightSurvYr), select = c(x, y))
# if(nrow(highlight_dat) > 0) {
# h_plot_list[[i]] <- p +
# geom_point(data = highlight_dat, aes(x = x, y = y), color = "turquoise2", size = 3)
# }
# }
# return(h_plot_list)
# }
FuncInitFilter <- function() {
shiny::req(!is.null(rv$dat))
# Initial default filtering of data so user can bypass filter page
rv_param_temp$defaultInputs$sel_YrRange <- c(min(rv$dat$MeteoYr, na.rm = TRUE), max(rv$dat$MeteoYr, na.rm = TRUE))
rv_param_temp$defaultInputs$sel_MinYrs <- 3
rv_param_temp$defaultInputs$sel_DefineSeasons <- "MeteoSeasons"
rv_param_temp$defaultInputs$sel_SummaryOrg <-sort(unique(rv$dat$OrganizationFormalName))
rv_param_temp$defaultInputs$sel_NPSparam <- "National Park Service Water Resources Division" %in% rv$dat$OrganizationFormalName
rv_param_temp$defaultInputs$sel_ActivityType <- sort(intersect(unique(rv$dat$ActivityTypeCode), c("Field Msr/Obs", "Field Msr/Obs-Portable Data Logger", "Sample", "Sample-Routine")))
rv_param_temp$defaultInputs$sel_ResultStatus <- sort(intersect(unique(rv$dat$ResultStatusIdentifier), c("Accepted", "Final", "Validated", "Historical")))
shiny::req(!is.null(rv_param_temp$defaultInputs$sel_NPSparam), !is.null(rv_param_temp$defaultInputs$sel_YrRange), !is.null(rv_param_temp$defaultInputs$sel_SummaryOrg), !is.null(rv_param_temp$defaultInputs$sel_ActivityType), !is.null(rv_param_temp$defaultInputs$sel_ResultStatus), !is.null(rv_param_temp$defaultInputs$sel_MinYrs))
rv_param_temp$selectCharSampleType <- FuncFilterSelectCharSampleType(
sel_NPSparam = rv_param_temp$defaultInputs$sel_NPSparam,
sel_YrRange = rv_param_temp$defaultInputs$sel_YrRange,
sel_SummaryOrg = rv_param_temp$defaultInputs$sel_SummaryOrg,
sel_ActivityType = rv_param_temp$defaultInputs$sel_ActivityType,
sel_ResultStatus = rv_param_temp$defaultInputs$sel_ResultStatus,
sel_MinYrs = rv_param_temp$defaultInputs$sel_MinYrs)
# Set initial plot input values
print("SETTING INITIAL THRESHOLD VALUES")
rv_param_temp$threshList <- NULL
print("SET THRESHLIST TO NULL")
rv_param_temp$currentInputs$sel_SummaryParam <- rv_param_temp$selectCharSampleType
rv_param_temp$currentInputs$sel_ThreshLower <- NA
rv_param_temp$currentInputs$sel_ThreshUpper <- NA
rv_param_temp$currentInputs$sel_ThreshCateg1 <- rv_param_temp$currentInputs$sel_ThreshCateg2 <- rv_param_temp$currentInputs$sel_ThreshCateg3 <- "good"
# session$sendCustomMessage(type = "resetValue", message = list("sel_SummaryParam", sort(rv_param_temp$selectCharSampleType)))
}
# FuncAddCategLevels <- function(subdat, )
FuncRefreshFilter <- function(sel_MinYrs, sel_SummaryParam, sel_SummaryOrg, sel_YrRange, sel_ActivityType, sel_ResultStatus, sel_DefineSeasons) {
# Update filter data to create rv_param_temp$subDat
shiny::req(!is.null(rv$importSettings$sel_Organization))
if(all(unique(rv$dat$OrganizationFormalName) %in% rv$importSettings$sel_Organization)==FALSE) {
rv_param_temp$subDat <- NULL
rv_param_temp$subDatYears <- NULL
rv_param_temp$subDatTypes <- NULL
} else {
shiny::req(!is.null(rv$dat), !is.null(sel_MinYrs), !is.null(sel_SummaryParam), !is.null(sel_SummaryOrg), !is.null(sel_YrRange), !is.null(sel_ActivityType), !is.null(sel_ResultStatus), !is.null(sel_DefineSeasons))
print("DOING FUNCREFRESHFILTER")
rv_param_temp$seasonType <- switch(
sel_DefineSeasons,
MeteoSeasons = "Calendar Year (starts Jan. 1)",
WaterSeasons = "Water Year (starts Oct. 1)",
CustomSeasons = paste0("Custom Year (starts ", as.character(input$sel_SeasonsStart, format="%b %d"), ")")
)
filterDat <- rv$dat
if(sel_DefineSeasons=="MeteoSeasons") {
filterDat$Yr <- as.integer(filterDat$MeteoYr)
filterDat$Mnth <- factor(filterDat$Mnth,levels(rv$dat$Mnth))
} else {
filterDat$Yr <- as.integer(filterDat$WaterYr)
filterDat$Mnth <- factor(filterDat$Mnth,levels(rv$dat$Mnth)[c(10,11,12,1:9)])
}
print("line731")
filterDat %<>%
dplyr::filter(Yr >= as.integer(sel_YrRange[1]) & Yr <= as.integer(sel_YrRange[2]) & OrganizationFormalName %in% sel_SummaryOrg & CharSampleType %in% sel_SummaryParam & ActivityTypeCode %in% sel_ActivityType & ResultStatusIdentifier %in% sel_ResultStatus)
print("line763")
# Assign custom seasons
if(nrow(filterDat) > 0 & sel_DefineSeasons %in% c("WaterSeasons", "CustomSeasons"))
{
filterDat <- FuncCustomSeasons(dat_df = filterDat, seas = sel_DefineSeasons)
}
rv$importSettings$sel_DefineSeasons <- sel_DefineSeasons
if(nrow(filterDat) > 0) {
filterYears <- filterDat %>%
dplyr::select(CharacteristicName, CharSampleType, MonitoringLocationIdentifier, Yr) %>%
dplyr::group_by(CharacteristicName, CharSampleType, MonitoringLocationIdentifier) %>%
dplyr::summarize(StartYr = as.integer(min(Yr, na.rm = TRUE)),
EndYr = as.integer(max(Yr, na.rm = TRUE)),
TotalSurveyYrs = dplyr::n_distinct(Yr),
NumRecords = n()) %>%
dplyr::filter(TotalSurveyYrs >= sel_MinYrs)
print("line780")
if(nrow(filterYears) > 0) { # if none of the data meet the minimum years criterion, these entries will be NULL
# Create ResultMeasureValue_replaced column that replaces values not detected
suppressWarnings(filterDat$ResultMeasureValue_replaced <- as.numeric(filterDat$ResultMeasureValue))
suppressWarnings(filterDat$ResultMeasureValue_replaced[filterDat$ResultDetectionConditionText != "Detected and Quantified" & is.na(filterDat$ResultMeasureValue) & !is.na(filterDat$DetectionQuantitationLimitMeasure.MeasureValue)] <-
as.numeric(filterDat$DetectionQuantitationLimitMeasure.MeasureValue[filterDat$ResultDetectionConditionText != "Detected and Quantified" & is.na(filterDat$ResultMeasureValue) & !is.na(filterDat$DetectionQuantitationLimitMeasure.MeasureValue)])) # create a column in which the detection limit replaces NA, for records where result was above or below detection limit--this column will be used to calculate probability quantiles <<<<<<<<<<<<<<< INCLUDE THIS EXPLANATION IN DOCUMENTATION
filterDat$ThreshCateg <- filterDat$CategName <- filterDat$CategResultMeasureValue <- NA # Create these columns so they can be filled if threshold or categorical color files are loaded. Also resets to NA when the filter data are changed.
# if(!is.null(rv_param_temp$threshList)) {
# print("ADDING THRESHOLD DATA TO FILTERED DATA FRAME")
# filterDat <- FuncAddThreshCateg(filterDat)
# }
rv_param_temp$subDat <- filterDat %>%
right_join(filterYears[, c("CharacteristicName", "CharSampleType", "MonitoringLocationIdentifier")], by = c("CharacteristicName", "CharSampleType", "MonitoringLocationIdentifier")) # just keep the ones that met the data filter criteria for total survey years, so these are the raw data that are summarized in rv_param_temp$subDatYears
if(!is.null(rv_param_temp$subDat)) {
rv_param_temp$subDatTypes <- as.data.frame(FuncDataTypes(dat = rv_param_temp$subDat))}
rv_param_temp$subDatYears <- filterYears
print("line785")
} else {
rv_param_temp$subDat <- NULL
rv_param_temp$subDatYears <- NULL
rv_param_temp$subDatTypes <- NULL
}
} else {
rv_param_temp$subDat <- NULL
rv_param_temp$subDatYears <- NULL
rv_param_temp$subDatTypes <- NULL
}
rm(filterDat, filterYears)
}
}
FuncPlotHeatMap <- function(dat, y_name, legend_range, legend_name) {
# Function to create static heatmaps. X-axis is always year.
#
# Args:
# dat: Data frame with these columns: Yr (for x-axis), Y, FillCol, MonitoringLocationIdentifier.
# y_name, legend_name: Axis labels and legend titles
#
# Returns:
# Static heat maps
#
# Create color scale
# min_colorval <- legend_range[1]
max_colorval <- legend_range[2] # make sure the range of color values is the same across all plots
template_cols <- viridisLite::viridis(n = max_colorval, alpha = 1, begin = 0, end = 1, direction = -1)
# # Calculate relative heights--This is generic to allow switching back to format where all characteristics are shown in a single page
# sites_per_char <- dat %>% dplyr::arrange(CharacteristicName) %>% dplyr::distinct(CharacteristicName, MonitoringLocationIdentifier) %>% dplyr::count(CharacteristicName) %>% dplyr::ungroup()
# sites_per_char <- sites_per_char[order(sites_per_char$CharacteristicName),] %>% dplyr::pull(n) # For some absurd reason, dplyr::arrange() is not competent in sorting so using base R to sort
# temp_distinct <- dat %>%
# dplyr::select(CharacteristicName, MonitoringLocationIdentifier, TimeUnit) %>% dplyr::distinct()
# rel_char_hts <- prop.table(sites_per_char) ### YES!!! This gets the heights correct. No need to try to account for title or x-axis labels, etc.--it's already adjusted for
# A ggplot object with NO data. Omit the characteristic from the facet_grid call
freq <- switch(input$sel_TimeSubunit, Season = "season", Mnth = "month")
p_title <- paste0(unique(dat$CharSampleType), ", # of surveys per ", freq)
p <- ggplot(dat) +
aes(x = Yr, y = TimeUnit, fill = FillCol) +
geom_tile(color = "gray") +
suppressWarnings(geom_text(aes(label = FillCol, colour = ifelse(FillCol > 5, "white", "black")))) +
scale_colour_manual(values=c("white"="white", "black"="black"), guide = "none") +
xlab(rv_param_temp$seasonType) +
labs(title = p_title) +
scale_x_continuous(expand=c(0, 0), breaks = seq(from = min(dat$Yr, na.rm = TRUE), to = max(dat$Yr, na.rm = TRUE), by = ifelse(diff(range(dat$Yr, na.rm = TRUE)) > 10, 2, 1)), limits = c(min(dat$Yr, na.rm = TRUE)-1, max(dat$Yr, na.rm = TRUE)+1)) + # Need to make limits wider b/c otherwise the fill color will be missing from the end columns. Setting the expand cuts out the empty space at beginning and end columns
scale_y_discrete(limits = rev) +
# scale_fill_viridis_c(direction = -1, na.value = "white", limits=c(1, max_colorval), name = legend_name) +
scale_fill_viridis_c(direction = -1, na.value = "white", limits=c(1, 12), oob=scales::squish, breaks = seq(1, 12, by = 2), name = legend_name) +
theme_bw(base_size = 14) +
lemon::facet_rep_wrap(~MonitoringLocationIdentifier, ncol =1, repeat.tick.labels = "bottom") +
theme(legend.position="top",
plot.title = element_text(size = 22)) +
# axis.text.x = element_text(angle = 90, hjust = 1)) +
theme(plot.margin=unit(c(3,3,1,2),"lines"))
print("779")
# # Build a separate graphic for each Characteristic
# char_list <- lapply(sort(unique(dat$CharacteristicName)), function(i) {
# p %+%
# subset(dat, CharacteristicName == i) + ggtitle(paste0(i, " (# of surveys per ", input$sel_TimeSubunit, ")"))
# })
# names(char_list) <-sort(unique(dat$CharacteristicName))
# print("785")
# # Build as Grobs and plot via gridExtra::grid.arrange
# final_heat_plots <- char_list %>%
# lapply(ggplotGrob) %>%
# arrangeGrob(grobs = ., heights = rel_char_hts) %>%
# grid.arrange(., ncol = 1)
# print("791")
# return(final_heat_plots)
return(p)
}
FuncParamAvailSites <- function(sel) {
shiny::req(!is.null(rv$sitesPointsSub), !is.null(rv_param_temp$subDat))
if(sel == "by_station") {
avail_sites <- rv$sitesPointsSub[rv$sitesPointsSub$MonitoringLocationIdentifier %in% unique(rv_param_temp$subDat$MonitoringLocationIdentifier),]
}
if(sel == "by_chartype") {
shiny::req(!is.null(input$sel_ShowCharType))
avail_sites <- rv$sitesPointsSub[rv$sitesPointsSub$MonitoringLocationIdentifier %in% unique(rv_param_temp$subDat$MonitoringLocationIdentifier[rv_param_temp$subDat$CharacteristicName %in% input$sel_ShowCharType]),]
}
return(avail_sites)
}
FuncPlotlyPieMatrix <- function(dat, discrete_cols, discrete_levels, plot_title) {
# Function to create plotly pie chart matrix of Threshold or Percentile categories, grouped by monitoring site (row) and year (col)
#
# Args:
# dat: Plot data with percentile/threshold classifications
# discrete_cols: For discrete fill, the vector of colors
# discrete_levels: For discrete fill, the levels corresponding with colors
# plot_title: Title for plot page
#
# Returns:
# Page of plotly pie charts
#
fig <- plot_ly(textfont = list(size = 25))
colors_list <- split(discrete_cols, discrete_levels)
m <- list(
l = 300,
r = 90,
b = 100,
t = 100,
pad = 0
)
dat$Color <- dplyr::recode(dat$CategVar, !!!colors_list)
yr_vec <- seq(from = min(dat$Yr, na.rm = TRUE), to = max(dat$Yr, na.rm = TRUE), by = 1)
for(row_num in 1:length(unique(dat$RowLev))) {
row_filter <- sort(unique(dat$RowLev))[row_num]
for(yr_num in 1:length(yr_vec)) {
this_yr <- yr_vec[yr_num]
pie_dat = subset(dat, RowLev == row_filter & Yr == this_yr)
if(nrow(pie_dat)>0) {
fig <- fig %>%
add_pie(data = pie_dat,
name = paste0(row_filter, "_", this_yr),
labels = ~CategVar,
values = ~n,
textposition = 'inside',
textinfo = 'label+percent',
insidetextfont = list(color = switch(("yellow" %in% discrete_cols)+1, "white", "black")),
hoverinfo = 'text',
text = ~HoverLabel,
marker = list(colors = ~Color, line = list(color = '#FFFFFF', width = 1)),
domain = list(row = row_num-1, column = yr_num-1))
}
}
}
width_px <- 420 + (110 * length(yr_vec)) # this is the plot width (paper)
height_px <- 200 + (110 * length(unique(dat$RowLev))) # this is the plot height (paper)
yr_seq_px <- seq(55, width_px-420, by = 110)/(110 * length(yr_vec)) # this is where year labels should align on x-axis, when reference is "paper"