-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.R
1796 lines (1593 loc) · 81.4 KB
/
app.R
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
# Project: GPSR shark MPA Project
# Objective: Generate a GUI for users to investigate conservation priorities for sharks and rays
# Species: All >1000 sharks and Rays
# Developer: Ross Dwyer
DateUpdated <- "06-Sep-2019" ## Date last updated
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
##############################################################################
# Libraries
##############################################################################
library(shiny)
library(ggplot2)
library(gtable)
library(grid)
library(leaflet)
library(sp)
library(rgdal)
library(raster)
library(RColorBrewer)
library(plotly)
library(dplyr)
library(DT)
library(tibble)
library(shinycssloaders)
library(highcharter)
library(fmsb)
##############################################################################
# Data
##############################################################################
#sharkdat <- read.csv("Data/IUCNFishbaseWeb.csv")
sharkdat <- read.csv("Data/IUCNFishbaseWebDispersal.csv")
names(sharkdat)[1] <- 'binomial' # Ensures continuity between pages
##Loads GIS files: reduced.MPAs,allspecrast,worldmap,orderrast,iucnrast ----
orderrast <- brick("GIS/ordersum_specrast.tif")
iucnrast <- brick("GIS/IUCNsum_specrast.tif")
allspecrast <- brick("GIS/multilayerspecrast.tif")
#reduced.MPAs <- readOGR(dsn="GIS",layer="simplifiedMPA")
# Works only on Windows!
##load('myMPA.RData') ##Loads GIS files: reduced.MPAs,allspecrast,worldmap,orderrast,iucnrast
#Works on Mac though had to sort errors on the loaded rasters
#library(repmis)
#source_data("https://github.com/RossDwyer/SharkRay-MPA/blob/master/myMPA.RData?raw=true")
# Load Country shapefile
reduced.countries <- readOGR(dsn="GIS/TM_WORLD_BORDERS_SIMPL-0.3","TM_WORLD_BORDERS_SIMPL-0.3")
# Load FAO areas shapefile and simplify topology for quick loading
# FAOs<- readOGR(dsn="GIS/FAO_AREAS","FAO_AREAS")
# library(rgeos)
# ## Extract Major FAOs
# FAOs_major.df = aggregate(FAOs, by = "F_AREA")
# FAOs_major.simple <- gSimplify(FAOs_major.df, tol = 1,topologyPreserve=TRUE)
# FAOs_major.simpledf <- SpatialPolygonsDataFrame(FAOs_major.simple, FAOs_major.df@data)
# writeOGR(FAOs_major.simpledf,dsn="GIS/FAO_AREAS",layer="FAO_AREAS_major_simple", driver="ESRI Shapefile",overwrite_layer = TRUE)
# ## Extract Minor FAOs
# FAOs.simple <- gSimplify(FAOs[,7], tol = 1,topologyPreserve=TRUE)
# ## Coerce to SpatialPolygonsDataFrame
# FAOs.simpledf <- SpatialPolygonsDataFrame(FAOs.simple, FAOs@data)
# writeOGR(FAOs.simpledf[1:8],dsn="GIS/FAO_AREAS",layer="FAO_AREAS_simple", driver="ESRI Shapefile",overwrite_layer = TRUE)
###
# tab 2B - visualise no species in FAOs/LMEs/EEZs
# Load simplified FAO and LME shapefiles for quick loading
#FAOsimple<- readOGR(dsn="GIS/FAO_AREAS","FAO_AREAS_simple")
FAO_major_simple <- readOGR(dsn="GIS","simplifiedFAO_counts")
FAO_sub_simple <- readOGR(dsn="GIS","simplifiedFAO_subarea_counts")
#FAO_major_simple <- readOGR(dsn="GIS/FAO_AREAS","FAO_AREAS_major_simple")
LMEsimple<- readOGR(dsn="GIS","simplifiedLME66")
#EEZsimple <- readOGR("GIS/eez_v10_mapshaper","eez_v10")
EEZsimple <- readOGR("GIS","simplifiedEEZ_counts1")
FAO_major_simple@data <- FAO_major_simple@data %>% select(Name_en,OCEAN,F_CODE,SURFACE,Nospecies,CR,EN,VU,rest)
FAO_sub_simple@data <- FAO_sub_simple@data %>% select(Name_en,OCEAN,F_CODE,SURFACE,Nospecies,CR,EN,VU,rest)
LMEsimple@data <- LMEsimple@data %>% select(LME_NAME,LME_NUMBER,Shape_Area,Nospecies,CR,EN,VU,rest)
EEZsimple@data <- EEZsimple@data %>% select(GeoName,Territory1,Sovereign1,ISO_Ter1,Area_km2,Nospecies,CR,EN,VU,rest)
EEZsimple <- EEZsimple[complete.cases(EEZsimple@data),] # removes na rows
#FAO_spec <- read.csv("Data/Sharks and rays in MAJOR FAOs_CRENVU.csv")
FAO_spec <- FAO_major_simple@data
# FAOsub_spec <- read.csv("Data/Sharks and rays in SUBAREA FAOs_CRENVU.csv")
FAOsub_spec <- FAO_sub_simple@data
#LME_spec <- read.csv("Data/Sharks and rays in LMEs_CRENVU.csv")
LME_spec <- LMEsimple@data
#EEZ_spec <- read.csv("Data/Sharks and rays in EEZs_CRENVU.csv")
EEZ_spec <- EEZsimple@data
# ivis <- 50 # No species in FAOs/LMEs/EEZ to visualise in the table
# sbarchart_colours <- rev(colorRampPalette(brewer.pal(9,"Blues")[-1])(ivis))
# FAO_spec1 <- data.frame(FAO_spec[order(FAO_spec$Nospecies,decreasing=TRUE),][1:ivis,],row.names=NULL)
# FAOsub_spec1 <- data.frame(FAOsub_spec[order(FAOsub_spec$Nospecies,decreasing=TRUE),][1:ivis,],row.names=NULL)
# LME_spec1 <- data.frame(LME_spec[order(LME_spec$Nospecies,decreasing=TRUE),][1:ivis,],row.names=NULL)
# EEZ_spec1 <- data.frame(EEZ_spec[order(EEZ_spec$Nospecies,decreasing=TRUE),][1:ivis,],row.names=NULL)
#sbarchart_colours <- rev(colorRampPalette(brewer.pal(9,"Blues")[-1]))
#EEZ_spec1 <- data.frame(EEZ_spec[order(EEZ_spec$Nospecies,decreasing=TRUE),],row.names=NULL)
#FAO_spec1 <- data.frame(FAO_spec[order(FAO_spec$Nospecies,decreasing=TRUE),],row.names=NULL)
#LME_spec1 <- data.frame(LME_spec[order(LME_spec$Nospecies,decreasing=TRUE),],row.names=NULL)
# Standardise column names and numbers for easy visualisation
sFAO_count <- data.frame(x=FAO_spec$Name_en, y=FAO_spec$Nospecies, y1=FAO_spec$CR, y2=FAO_spec$EN, y3=FAO_spec$VU, y4=FAO_spec$rest, x1=FAO_spec$F_CODE, Area=FAO_spec$SURFACE)
sFAOsub_count <- data.frame(x=FAOsub_spec$Name_en, y=FAOsub_spec$Nospecies, y1=FAOsub_spec$CR, y2=FAOsub_spec$EN, y3=FAOsub_spec$VU, y4=FAOsub_spec$rest, x1=FAOsub_spec$F_CODE, Area=FAOsub_spec$SURFACE)
sLME_count <- data.frame(x=LME_spec$LME_NAME, y=LME_spec$Nospecies, y1=LME_spec$CR, y2=LME_spec$EN, y3=LME_spec$VU, y4=LME_spec$rest, x1=LME_spec$LME_NUMBER, Area=LME_spec$Shape_Area)
sEEZ_count <- data.frame(x=EEZ_spec$GeoName, y=EEZ_spec$Nospecies, y1=EEZ_spec$CR, y2=EEZ_spec$EN, y3=EEZ_spec$VU, y4=EEZ_spec$rest, x1=EEZ_spec$Territory1, Area=EEZ_spec$Area_km2)
# Add 'threatened' category
sEEZ_count <- sEEZ_count %>% mutate(y5 = y1 + y2 + y3)
sFAO_count <- sFAO_count %>% mutate(y5 = y1 + y2 + y3)
sFAOsub_count <- sFAOsub_count %>% mutate(y5 = y1 + y2 + y3)
sLME_count <- sLME_count %>% mutate(y5 = y1 + y2 + y3)
## tab 1 species lookup table
order.name <- c("CARCHARHINIFORMES",
"CHIMAERIFORMES",
"HETERODONTIFORMES",
"HEXANCHIFORMES",
"LAMNIFORMES",
"ORECTOLOBIFORMES",
"PRISTIOPHORIFORMES",
"RAJIFORMES",
"SQUALIFORMES",
"SQUATINIFORMES")
# Edit dataframe to include web links - note: target="_blank" ensures links opened in a new tab
sharkdat <- sharkdat %>%
mutate(
web_redlist = sprintf('<a href="%s" target="_blank" class="btn btn-link">iucnredlist.org</a>',web_redlist),
#assessment_redlist = sprintf('<a href="%s" target="_blank" class="btn btn-primary">PDF</a>',assessment_redlist),
web_fishbase = sprintf('<a href="%s" target="_blank" class="btn btn-link">fishbase.org</a>',web_fishbase),
pointborder = "1"
) %>%
select(FBname,
#CommonName,
order_name,family_nam,
binomial,
Length,
DemersPelag,Vulnerability,Resilience,
code,web_redlist,web_fishbase,
MarkRecapt_tags,MarkRecapt_mean,MarkRecapt_sd,passive_tags,passive_mean,passive_sd,satellite_tags,satellite_mean,
pointborder)
levels(sharkdat$Resilience) <- c("Very low", "Low", "Medium", "High")
#Read in Dispersal distance data
Df <- read.csv("Data/DispersalKernel_Properties.csv")
# Add a column detailing if we have Dispersal distance data for a species
sharkdat$DispersalKernel <- "No"
for (i in 1:nrow(Df)){
inum <- which(as.character(sharkdat$binomial)==as.character(Df$ScientificName[i]))
sharkdat$DispersalKernel[inum] <- "Yes"
}
# Function to make the empty dispersal plot
makeDispersalplot <- function(xmax){
xx <- seq(0, log(xmax), length=1000)
yy <- rep(0,length(xx))
#par(oma = c(0.1,1,2,1.5))
par(mar = c(4, 4, 2, .5), font.axis = 2,font.lab = 2) # stops the arial font issue
plot(x=xx,y=yy, xaxt="n", las=1,
xlab="Maximum dispersal distance (km)",
ylab="Probability of dispersal", type="n",ylim=c(0,1),
bty="l")
axis(1, at= log(c(0.01, seq(0.1,1,l=10),
seq(1,10,l=10),seq(10,100,l=10),
seq(100,1000,l=10),
seq(1000,10000,l=10))+1), labels=F, tcl=-0.3)
axis(1, at= log(c(0.1,1,10,100,1000,10000)+1),
labels=c(0.1,1,10,100,1000,10000))
legend("top",bty="n",
inset = c(0,-0.13),
xpd = TRUE, horiz = TRUE,
lty=1,lwd=2,
col=c(1:3),
legend = c("Mark-recapture",
"Passive acoustic",
"Satellite"))
}
# Function to make the empty landings plot
makeLandingsplot <- function(xmax){
xd <- seq(1950, 2010, by=1)
yd <- rep(0,0,length(xd))
#par(oma = c(0.1,1,2,1.5))
par(mar = c(4, 4, 2, .5), font.axis = 2,font.lab = 2) # stops the arial font issue
plot(x=xd,y=yd, las=1,
xlab="Year",
ylab="Reported catch landings ('000 t)", type="n",
ylim=c(0,600),
bty="l")
# legend("top",bty="n",
# inset = c(0,-0.13),
# xpd = TRUE, horiz = TRUE,
# lty=1,lwd=2,
# col=c(1:3),
# legend = c("Mark-recapture",
# "Passive acoustic",
# "Satellite"))
}
iucnimg <- paste0('img/DD.png')
iucnlink <- paste0("https://github.com/RossDwyer/SharkRay-MPA/blob/master/img/DD.png")
sharkdat$flag <- ifelse(sharkdat$code=='CR','<img src=img/CR.png> </img>',
ifelse(sharkdat$code=='EN','<img src=img/EN.png> </img>',
ifelse(sharkdat$code=='VU','<img src=img/VU.png> </img>',
ifelse(sharkdat$code=='NT','<img src=img/NT.png> </img>',
ifelse(sharkdat$code=='LC','<img src=img/LC.png> </img>',
'<img src=img/DD.png> </img>')))))
cleantable <- sharkdat %>%
select(FBname,
order_name, family_nam,
binomial,
Length,
DemersPelag,
DispersalKernel,
Vulnerability,Resilience,
flag,
web_redlist,
#assessment_redlist,
web_fishbase)
# tab 1a - species distribution maps
species.name <- sharkdat$binomial # Names of species for the species range maps
#pal <- c("#253494","#f93") # HEX code for the colour of the raster [1] and the MPAs [2]
pal <- c("#de2d26","#f93")
###
# tab 2 - Country EEZ datasets
CI_FinalPCA_spec <- read.csv("Data/CI_Database_FinalPCA_with_species.csv")
# merge function with the duplicateGeoms argument set to TRUE
# if TRUE geometries in x are duplicated if there are multiple matches between records in x and y
CL2sp <- sp::merge(reduced.countries, CI_FinalPCA_spec, by.x="ISO3",by.y= "ISO_Ter1",
all=F,duplicateGeoms = TRUE)
# Choose the columns and the orders. Note order needs to match renaming in DT
CL2sp@data <- CL2sp@data[,c("GeoName","Territory1","ISO3","Sovereign1","Area_km2",
"EconomicVulnerability","DependMarineResource","Education",
"Tourism","Corruption","ChallengeIndex",
"OpportunityIndex","CLI",
"Nospecies","Threatened",
"CR","EN","VU","rest")]
## Round SocioEco values to 2 Dec places
CL2sp@data$EconomicVulnerability <- round(CL2sp@data$EconomicVulnerability, digits=2)
CL2sp@data$DependMarineResource <- round(CL2sp@data$DependMarineResource, digits=2)
CL2sp@data$Education <- round(CL2sp@data$Education, digits=2)
CL2sp@data$Tourism <- round(CL2sp@data$Tourism, digits=2)
CL2sp@data$Corruption <- round(CL2sp@data$Corruption, digits=2)
CL2sp@data$ChallengeIndex <- round(CL2sp@data$ChallengeIndex, digits=2)
CL2sp@data$OpportunityIndex <- round(CL2sp@data$OpportunityIndex, digits=2)
CL2sp@data$CLI <- round(CL2sp@data$CLI, digits=2)
CL2sp@data$Area_km2 <- round(CL2sp@data$Area_km2, digits=1)
## Spider / radar plot
socioeconomic_devel <- CL2sp@data %>%
filter(is.na(ChallengeIndex)==FALSE)#,
iMax <- socioeconomic_devel%>%
summarize(Corruption=max(Corruption),
EconomicVulnerability=max(EconomicVulnerability),
Tourism=max(Tourism),
DependMarineResource=max(DependMarineResource),
Education=max(Education))
iMin <- socioeconomic_devel%>%
summarize(Corruption=min(Corruption),
EconomicVulnerability=min(EconomicVulnerability),
Tourism=min(Tourism),
DependMarineResource=min(DependMarineResource),
Education=min(Education))
###
# tab 3 (Shark MPA page)
SharkMPAs_coords <- read.csv("Data/Table 1 Shark MPA draft with coords.csv")
# legend html generator:
markerLegendHTML <- function(IconSet) {
# container div:
legendHtml <- "<div style='padding: 10px; padding-bottom: 10px;'><h4 style='padding-top:0; padding-bottom:10px; margin: 0;'> Shark MPA </h4>"
n <- 1
# add each icon for font-awesome icons icons:
for (Icon in IconSet) {
if (Icon[["library"]] == "fa") {
legendHtml<- paste0(legendHtml, "<div style='width: auto; height: 45px'>",
"<div style='position: relative; display: inline-block; width: 36px; height: 45px' class='awesome-marker-icon-",Icon[["markerColor"]]," awesome-marker'>",
"<i style='margin-left: 8px; margin-top: 11px; 'class= 'fa fa-",Icon[["icon"]]," fa-inverse'></i>",
"</div>",
"<p style='position: relative; top: -20px; display: inline-block; ' >", names(IconSet)[n] ,"</p>",
"</div>")
}
n<- n + 1
}
paste0(legendHtml, "</div>")
}
createLink <- function(val) {
sprintf('<a href="https://www.google.com/#q=%s" target="_blank" class="btn btn-primary">Info</a>',val)
}
IconSet <- awesomeIconList(
"Entire EEZ" = makeAwesomeIcon(icon= 'star', markerColor = 'green', library = "fa"),
"Part EEZ" = makeAwesomeIcon(icon= 'star', markerColor = 'blue', library = "fa")
)
###
# tab 3A - For the order/IUCN hotspot maps
iorder <- orderrast[[1]]
iCARCHARHINIFORMES <- orderrast[[2]]
iCHIMAERIFORMES <- orderrast[[3]]
iHETERODONTIFORMES <- orderrast[[4]]
iHEXANCHIFORMES <- orderrast[[5]]
iLAMNIFORMES <- orderrast[[6]]
iORECTOLOBIFORMES <- orderrast[[7]]
iPRISTIOPHORIFORMES <- orderrast[[8]]
iRAJIFORMES <- orderrast[[9]]
iSQUALIFORMES <- orderrast[[10]]
iSQUATINIFORMES <- orderrast[[11]]
istatus <- iucnrast[[1]]
iCR <- iucnrast[[2]]
iEN <- iucnrast[[3]]
iNT <- iucnrast[[4]]
iVU <- iucnrast[[5]]
iLC <- iucnrast[[6]]
iDD <- iucnrast[[7]]
iCREN <- iucnrast[[8]]
iCRENVU <- iucnrast[[9]]
# Colour scale for the category maps
scolours.ord <- c("#e5f5e0", "#a1d99b", "#31a354")
scolours.iucn <- c("#fee0d2", "#fc9272", "#de2d26")
###
# tab 4 (About page)
noSpecies <- length(species.name) # number of species considered
# User interface ----
PageTitle <- "App for Conservation status of Sharks and Rays"
##############################################################################
# UI Side
##############################################################################
ui <- navbarPage(
## Add the Shark Conservation Fund logo
# titlePanel(#windowTitle = PageTitle, # Failed attempt to
#title =
# div(
img(
src = "img/shark-conservation-fund-lock-up-blk-RGB.jpg",
height = 50,
width = 150,
style = "margin:-15px 0px; padding-top:-10px",
alt="Shark Conservation Fund"
),
## TAB 1
tabPanel(title="Species explorer",
fluidPage(
# Top left panel
column(4, plotOutput('x2', height = 350),
column(12,radioButtons(inputId = "sMakePlots",
label = "Select which plot to visualise:",
choices = c("Vulnerability"= "sVulnPlot",
"Dispersal distances" = "sDistPlot",
"Landings per year" = "sSpLandYr"),
selected = "sVulnPlot",
inline = TRUE))
),
# Top right panel
column(8,
leafletOutput("mapSpecies", width = '100%',height=350) %>%
withSpinner(color="#3182bd")),
br(),
br(),
# Conditional panel if rows HAVE NOT been selected from the species data table, show text
conditionalPanel(
condition = "input.speciestable_rows_selected < 1",
fluidRow(column(4,helpText("Select from the table below which species to visualise.")))),
# Conditional panel if rows HAVE been selected from the species data table, show DOWNLOAD button
conditionalPanel(
condition = "input.speciestable_rows_selected >= 1",
fluidRow(column(4,downloadButton('speciesReport', "Download Species Report")))),
br(),
br(),
# Bottom panel
DT::dataTableOutput("speciestable", width = '100%', height = 200)
)
),
## TAB 2
tabPanel(title="Region explorer",
fluidPage(
# Top panel
fluidRow(
column(4,
#absolutePanel(top = 0, left = 0,
radioButtons(inputId= "layerOverlap",
label = "Sort by:",
choices = c("IUCN listing" = "iucn", "Taxonomic order"= "order"),
selected = "iucn",
inline = FALSE),
conditionalPanel(
condition = "input.layerOverlap == 'iucn'",
selectInput("var.iucn",
label = "IUCN codes",
choices = list("all",
"CR+EN+VU",
"CR+EN",
"CR",
"EN",
"VU",
"NT",
"LC",
"DD"),
selected = "all"),
sliderInput("range2",
"Upper % species displayed :",
min = 0, max = 100, step = 10, value = 100)
),
conditionalPanel(
condition = "input.layerOverlap == 'order'",
selectInput("var.order",
label = "Taxonomic orders",
choices = list("all",
"CARCHARHINIFORMES",
"CHIMAERIFORMES",
"HETERODONTIFORMES",
"HEXANCHIFORMES",
"LAMNIFORMES",
"ORECTOLOBIFORMES",
"PRISTIOPHORIFORMES",
"RAJIFORMES",
"SQUALIFORMES",
"SQUATINIFORMES")),#,selected = "all"),
sliderInput("range1",
"Upper % species displayed :",
min = 0, max = 100, step = 10, value = 100)
# )
),
br(),
# Select which regions to visualise
selectInput("sAreaPolygons",
label = "Select which areas to visualise:",
#choices = list("sFAO_count","sFAOsub_count","sLME_count","sEEZ_count"),
choices = list("FAO Regions" = "sFAO_count",
"FAO Subareas" = "sFAOsub_count",
"Large Marine Ecosystems" = "sLME_count",
"Exclusive Economic Zones"= "sEEZ_count"),
selected = "sFAO_count")
),
# Plot the map
column(8,
leafletOutput("mapRegion", width = "100%", height = 350) %>%
withSpinner(color="#3182bd"))
),
# tags$div(class="header", checked=NA,
# tags$strong("This plot displays the number of shark and ray species present in marine and coastal regions")),
#
fluidRow(
column(4,
# Select which dataset to visualise
radioButtons(inputId = "sSelectRegionDisplay",
label = "Show data as:",
choices = c("Raw data"= "SRANKSDT",
"Stacked barplot" = "sRegionPlot"),
selected = "SRANKSDT",
inline = TRUE)),
column(4,
selectInput("tab.order",
label = "Sort the data by the following feature",
choices = list("No Species","Threatened Species","Area"),
selected = "No Species"))),
# If selected draw christmas tree figures
conditionalPanel(
condition = "input.sSelectRegionDisplay == 'sRegionPlot'",
plotlyOutput("plot", width = "100%", height = "100%") %>%
withSpinner(color="#3182bd")
),
# If MPA selected by radio button, draw the MPA data table
conditionalPanel(
condition = "input.sSelectRegionDisplay == 'SRANKSDT'",
DT::dataTableOutput('RegionTable')
),
verbatimTextOutput("event"),
tags$div(class="header", checked=NA,
tags$p("For more information about the regions, click the links below..."),
tags$a(href="https://www.vlis.be/en/imis?module=dataset&dasid=5465", "Exclusive Economic Zones | "),
tags$a(href="http://www.fao.org/fishery/area/search/en", "FAO Regions | "),
tags$a(href="http://www.lme.noaa.gov/index.php?option=com_content&view=article&id=1&Itemid=112", "Large Marine Ecosystems")
)
#)
)
),
## TAB 3
tabPanel(title="Country explorer",
fluidPage(
# Top panel
fluidRow(
column(4,
selectInput("tab.x3z",
label = "Select Z axis",
choices = list("Area_km2",
"DependMarineResource","Education",
"Tourism","Corruption",
"EconomicVulnerability",
"ChallengeIndex","OpportunityIndex","CLI",
"Nospecies","Threatened",
"CR","EN","VU","rest"),
selected = "Threatened")#,
#actionButton("runif", "Go!")
),
column(8,
leafletOutput("mapCounty", width = '100%', height = 350) %>%
withSpinner(color="#3182bd")
)),
#Middle Panel
fluidRow(
column(2,
selectInput("tab.x3x",
label = "Select X axis",
choices = list("Area_km2",
"DependMarineResource","Education",
"Tourism","Corruption",
"EconomicVulnerability",
"ChallengeIndex","OpportunityIndex","CLI",
"Nospecies","Threatened",
"CR","EN","VU","rest"),
selected = "DependMarineResource"),
selectInput("tab.x3y",
label = "Select Y axis",
choices = list("Area_km2",
"DependMarineResource","Education",
"Tourism","Corruption",
"EconomicVulnerability",
"ChallengeIndex","OpportunityIndex","CLI",
"Nospecies","Threatened",
"CR","EN","VU","rest"),
selected = "Threatened")
),
column(4,
plotlyOutput('x3', height = 300)),
column(3,
plotOutput('xspider', height = 300)),
column(3,
plotlyOutput('xthreatbar', height = 300))
),
# fluidRow(
# column(6,
# sliderInput(
# inputId = "sld21_ChallengeIndex",
# label="Challenge index:",
# min=min(CL2sp@data$ChallengeIndex,na.rm=T), max=max(CL2sp@data$ChallengeIndex,na.rm=T),
# value=c(min(CL2sp@data$ChallengeIndex,na.rm=T),max(CL2sp@data$ChallengeIndex,na.rm=T)),
# step=0.1,round=1),
# sliderInput(
# inputId = "sld22_OpportunityIndex",
# label="Opportunity index:",
# min=min(CL2sp@data$OpportunityIndex,na.rm=T), max=max(CL2sp@data$OpportunityIndex,na.rm=T),
# value=c(min(CL2sp@data$OpportunityIndex,na.rm=T),max(CL2sp@data$OpportunityIndex,na.rm=T)),
# step=0.1,round=1)
# ),
# column(6,
# sliderInput(
# inputId = "sld23_CLI",
# label="Conservation likelihood index:",
# min=min(CL2sp@data$CLI,na.rm=T), max=max(CL2sp@data$CLI,na.rm=T),
# value=c(min(CL2sp@data$CLI,na.rm=T),max(CL2sp@data$CLI,na.rm=T)),
# step=0.1,round=1),
# sliderInput(
# inputId = "sld24_Threatened",
# label="No. threatened species:",
# min=min(CL2sp@data$Threatened,na.rm=T), max=max(CL2sp@data$Threatened,na.rm=T),
# value=c(min(CL2sp@data$Threatened,na.rm=T),max(CL2sp@data$Threatened,na.rm=T)),
# step=1,round=1)
# )
# )
# ),
# Bottom panel
DT::dataTableOutput("countryTable", width = '100%', height = 200)
)
),
## TAB 4
tabPanel(title="About",
tags$body(
h4('This Shiny App was built to help visualise shark and ray distribution information across the globe'),
p('The purpose of the tool is to help identify priority areas on a global scale where spatial protection would provide the greatest benefit to shark and ray conservation efforts.'),
br(),
p('The app was funded by <a href="www.sharksandrays.org">The Shark Conservation Trust</a> (formally the Global Partnership for Sharks & Rays), a sponsored project of Rockefeller Philanthropy Advisors.'),
p('It contains range distribution information of 1083 shark and ray species downloaded from <a href="%22http://www.iucnredlist.org%22">The IUCN Red List of Threatened Species</a>.'),
br(),
a(href = "For more information, visit www.sharksandrays.org", "For more information, visit www.sharksandrays.org"),
br(),
br(),
br(),
p("The application was build and maintained by Dr Ross Dwyer and is powered by...")),
#tags$img(src = "https://www.rstudio.com/wp-content/uploads/2014/07/RStudio-Logo-Blue-Gradient.png", width = "180px", height = "60px"),
#tags$img(src = "http://www.mcclellandlegge.com/img/shiny-logo.png", width = "100px", height = "100px"),
#tags$img(src = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/13/Leaflet_logo.svg/2000px-Leaflet_logo.svg.png", width = "180px", height = "60px"),
tags$img(src = "img/RStudio-Logo-Blue-Gradient.png", width = "180px", height = "60px"),
tags$img(src = "img/shiny-logo.png", width = "100px", height = "100px"),
tags$img(src = "img/Leaflet_logo.svg.png", width = "180px", height = "60px"),
br(),
a(href = "https://github.com/RossDwyer","Our project is on GitHub"),
br(),
br(),
p(paste0("Date last updated: ",DateUpdated))
)
)
##############################################################################
# Server Side
##############################################################################
# server logic required to draw the map ----
server <- function(input, output, session) {
#### TAB 1: Species Explorer map and table ####
# Top left panel - Plot the map with no species selected
output$mapSpecies <- renderLeaflet({
leaflet() %>%
setView(lng = 0, lat = 0, zoom = 1) %>%
addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
addLegend(colors = pal[1],
labels = c("Select a species")) %>%
addPolygons(data=FAO_major_simple, # Add FAO layers
smoothFactor = 0.2,
stroke = TRUE,weight=1,
opacity = 1.0, fillOpacity = 0.1,
color = "white",
popup = ~Name_en,
highlightOptions = highlightOptions(color = "white",weight = 2,bringToFront = TRUE),
dashArray = "3",
group = "FAO_regions") %>%
addPolygons(data=FAO_sub_simple, # Add FAO subarea layers
smoothFactor = 0.2,
stroke = TRUE,weight=1,
opacity = 1.0, fillOpacity = 0.1,
color = "white",
popup = ~Name_en,
highlightOptions = highlightOptions(color = "white",weight = 2,bringToFront = TRUE),
dashArray = "3",
group = "FAO_subareas") %>%
addPolygons(data=LMEsimple, # Add LME layers
smoothFactor = 0.2,
stroke = TRUE,weight=1,
opacity = 1.0, fillOpacity = 0.1,
color = "white",
popup = ~LME_NAME,
highlightOptions = highlightOptions(color = "white",weight = 2,bringToFront = TRUE),
dashArray = "3",
group = "LMEs") %>%
addPolygons(data=EEZsimple, # Add EEZ layers
smoothFactor = 0.2,
stroke = TRUE,weight=1,
opacity = 1.0, fillOpacity = 0.1,
color = "white",
popup = ~GeoName,
highlightOptions = highlightOptions(color = "white",weight = 2,bringToFront = TRUE),
dashArray = "3",
group = "EEZs") %>%
addLayersControl(baseGroups = c("OSM (default)"), # Layers control
overlayGroups = c("FAO_regions","FAO_subareas","LMEs","EEZs","IUCN"),
options = layersControlOptions(collapsed = TRUE)) %>%
# addControl(html = markerLegendHTML(IconSet = IconSet),
# position = "bottomright") %>%
hideGroup(group=c("FAO_regions","FAO_subareas","LMEs","EEZs"))
})
# Top right panel - Choose which plot to visualise
observeEvent(input$sMakePlots, {
output$x2 <- renderPlot({
par(mar = c(4, 4, 1, .1), font.axis = 2,font.lab = 2) # stops the arial font issue
if (input$sMakePlots == 'sVulnPlot'){
ggplot(data = sharkdat,
aes(x = code, y = Vulnerability,
fill = pointborder,colour = pointborder
)) +
geom_dotplot(dotsize = 0.4,binwidth = 2,
binaxis = "y", stackdir = "center", binpositions="all") +
scale_fill_manual(values=c("#d3d3d3"))+
scale_color_manual(values=c("#d3d3d3"))+
scale_x_discrete(limits=c("CR", "EN", "VU", "NT", "LC", "DD"))+
labs(title="",x="IUCN code", y = "Vulnerability Index")+
theme_minimal()+
theme(legend.position="none") # Remove legend
}
if (input$sMakePlots == 'sDistPlot')
makeDispersalplot(1500)
if (input$sMakePlots == 'sSpLandYr')
makeLandingsplot()
})
})
# Choose which species to visualise on the map and in the plots using the datatable
observeEvent(input$speciestable_rows_selected, {
x <- input$speciestable_rows_selected # Assign the row number of the species to display
specName <- sharkdat$binomial[x] # Assign the species name
newdata <- allspecrast[[x]] # Assign the species raster
newdata[newdata <= 0] <- NA
proxy <- leafletProxy("mapSpecies")
proxy %>%
clearImages() %>% # removes earlier rasters
clearControls() %>% # # removes earlier legends
addLegend(colors = pal[1], # Adds new legend with species name (binomial)
position = "topright",
labels = specName) %>%
addRasterImage(layerId ="layer2",
newdata,
colors=pal[1],
opacity = 0.5,
group = "Species") %>%
mapOptions(zoomToLimits = "first")
observeEvent(input$sMakePlots, {
# select what plot to visualise
if (input$sMakePlots == 'sVulnPlot'){
sharkdat2 <- sharkdat # So that our dataset isn't overwritten
output$x2 <- renderPlot({
draw_vul <- function(x1){
# If a row has been selected - make border a different colour
if (length(x1)) sharkdat2$pointborder[x1] <- "2"
ggplot(data = sharkdat2,
aes(x = code, y = Vulnerability,
fill = pointborder,colour = pointborder)) +
geom_dotplot(dotsize = 0.4,binwidth = 2,
binaxis = "y", stackdir = "center", binpositions="all") +
##geom_hline(col = "#b63737")# + # Add marker lines here for Y axis??
##geom_vline(col = "#b63737")## Add marker lines here for X axis??
scale_fill_manual(values=c("#d3d3d3", "#b63737"))+
scale_color_manual(values=c("#d3d3d3", "#b63737"))+
scale_x_discrete(limits=c("CR", "EN", "VU", "NT", "LC", "DD"))+
labs(title = "",x = "IUCN code", y = "Vulnerability Index")+
theme_minimal()+
theme(legend.position="none") # Remove legend
}
draw_vul(x)
})
}
if (input$sMakePlots == 'sDistPlot'){
output$x2 <- renderPlot(
{
displot2 <- function(data, species,
xmax=1500,
xlab="Maximum dispersal distance (km)",
ylab="Probability of dispersal", ...){
makeDispersalplot(xmax)
dat <- data[data$ScientificName %in% species,]
xx <- seq(0, log(xmax), length=1000)
if(nrow(dat)==0){
graphics::text(5,0.5, "No dispersal data available for this species...")
graphics::text(5,0.4, "Please select another row")
}else{
dat_mark_recap <- dat[dat$tag_type %in% "mark_recap",]
dat_passive <- dat[dat$tag_type %in% "passive",]
dat_satellite <- dat[dat$tag_type %in% "satellite",]
if(nrow(dat_mark_recap)>0){
yfit <- dgamma(xx, shape=dat_mark_recap$shape, scale=dat_mark_recap$scale)
yy <- yfit/max(yfit)
lines(xx, yy, col=1, lwd=2)
}
if(nrow(dat_passive)>0){
yfit <- dgamma(xx, shape=dat_passive$shape, scale=dat_passive$scale)
yy <- yfit/max(yfit)
lines(xx, yy, col=2, lwd=2)
}
if(nrow(dat_satellite)>0){
yfit <- dgamma(xx, shape=dat_satellite$shape, scale=dat_satellite$scale)
yy <- yfit/max(yfit)
lines(xx, yy, col=3, lwd=2)
}
}
}
###
displot2(data = Df,
species = as.character(specName))
})
}
if (input$sMakePlots == 'sSpLandYr'){
output$x2 <- renderPlot(
{
makeLandingsplot()
graphics::text(1990,300, "No landings data available for this species...")
graphics::text(1990,250, "Please select another row")
# }
# landplot1 <- function(data, species,
# xmax=1500,
# xlab="Maximum dispersal distance (km)",
# ylab="Probability of dispersal", ...){
#
# #makeLandingsplot()
#
# dat <- data[data$ScientificName %in% species,]
# xx <- seq(0, log(xmax), length=1000)
#
# if(nrow(dat)==0){
# graphics::text(5,0.5, "No dispersal data available for this species...")
# graphics::text(5,0.4, "Please select another row")
# }else{
#
# dat_mark_recap <- dat[dat$tag_type %in% "mark_recap",]
# dat_passive <- dat[dat$tag_type %in% "passive",]
# dat_satellite <- dat[dat$tag_type %in% "satellite",]
#
# }
# }
# displot2(data = Df,
# species = as.character(specName))
})
}
})
})
## Generate Species data explorer table
output$speciestable <- DT::renderDataTable(
{
datatable(cleantable,
options=list(
pageLength = 5, # number of rows per page
scrollX = TRUE,
autoWidth = TRUE,
searchHighlight = TRUE, #Highlight searchesd text with yellow
columnDefs = list(list(#width = '50px',
targets = 1,
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 30 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 30) + '...</span>' : data;",
"}")
))),
caption = 'Search species information table', # <a href="#" onclick="alert('This script allows you to write help text for an item');">help me</a> #
filter = 'top',
selection = 'single', # selects only one row at a time
rownames = FALSE, # no row names
colnames=c("Common name",
'Order name', 'Family name',
'Species name',
'Total length (cm)',
'Habitat','Disperal data',
'Vulnerability index', 'Resilience',
'IUCN threat category',
'IUCN web',
#'Download IUCN assessment',
'Fishbase web'),
callback = JS("var tips = ['The common English name for the species', 'The Order the species belongs to', 'The Family the species belongs to',
'Genus and species name',
'Max reported total length in cm (Fishbase). For sharks this is measured as a straight line from the tip of the snout to the end of the upper caudal fin lobe. Ray sizes are also given as total lengths.',
'Indicates the particular environment preferred by the species (Fishbase)',
'Is there Satellite, Acoustic or Recapture data available?',
'Vulnerability value provided by Fishbase', 'Estimate of sp[ecies resilience from FishBase. Describes the ability of a species population to recover after a perturbance', 'IUCN threat listing'],
header = table.columns().header();
for (var i = 0; i < tips.length; i++) {
$(header[i]).attr('title', tips[i]);
}"),
#callback = JS('table.page(3).draw(false);'),
#initComplete = JS(
# "function(settings, json) {",
# "$(this.api().table().header()).css({'font-size': '90%'});",
# "}"),
#class = 'white-space: nowrap', # stops wrapping of rows
escape = FALSE # This bit is to stop the links from rendering literally (i.e. text only)
)
#formatStyle(columns = c(1:10), fontSize = '80%')
}
)
###
# This generates the species report .html file
output$speciesReport <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "species_report.html",
content = function(file) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "species_report.Rmd")
file.copy("species_report.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
params <- list(nspeciestable = input[["speciestable_rows_selected"]],
speciesdata = sharkdat,
speciesrast = allspecrast[[input[["speciestable_rows_selected"]]]]
)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
#### TAB 2: Regional explorer featuring hotspot map and region details ####
# # Arrange MPAdata in format for plots and mapping
# lats <- SharkMPAs_coords[,"Lat"]
# longs <- SharkMPAs_coords[,"Long"]
# popups <- SharkMPAs_coords[,"Shark.Marine.Protected.Areas"]
# layerids <- SharkMPAs_coords[,"Shark.Marine.Protected.Areas"]
# iconNames <- ifelse(SharkMPAs_coords[,"Entire.EEZ"] == "Y", "star", "star")
# iconColors <- ifelse(SharkMPAs_coords[,"Entire.EEZ"] == "Y", "green", "blue")
# locationRanks <- data_frame(Name = popups,
# Date=SharkMPAs_coords[,"Date"],
# Area.km2=SharkMPAs_coords[,"Area..km2."],
# Territory.name=SharkMPAs_coords[,"Territory.name"],
# Sovereign=SharkMPAs_coords[,"Sovereign"],
# Entire.EEZ=SharkMPAs_coords[,"Entire.EEZ"],
# Source=createLink(SharkMPAs_coords[,"Source"]),
# lats,longs, popups,layerids,iconNames,iconColors)
# # Convert the dataframe to an interactive DataTable
# d1 <- datatable(locationRanks[,c("Name", "Date",
# "Area.km2", "Territory.name",
# "Sovereign","Entire.EEZ",
# "Source")],
# caption = 'Search country information table',
# selection = 'single', # selects only one row at a time
# rownames=FALSE, # no row names
# colnames=c("Name", "Date installed",
# 'Area (km2)', 'Territory',
# 'Sovereign', 'Entire EEZ?',
# 'Source'),
# escape = FALSE,