-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRVC_diversity_analysis.Rmd
7277 lines (5832 loc) · 298 KB
/
RVC_diversity_analysis.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: "Florida Keys Reef Fish Biodiversity"
author: "Megan Hepner"
date: "April 28, 2017"
output: html_document
---
Rstudio Version 1.2.5019
R 3.6.1 GUI 1.70 El Capitan build (7684)
### Inputs
1. species-trait matrix
1. psu abundance dataframe
1. psu biomass dataframe
### Outputs
1. Functional dendogram (Fig: The final ultrametric functional dendrogram for 348 reef fish in the Florida Keys obtained using hierarchial agglometric clustering.)
+ Trait-matrix visualization
1. By *strata* for each sampling year (using PSU data)
+ Mean abundance and plot
+ Mean biomass and plot
+ Richness as effective number of species and plot
+ Simpson diversity as effective number of species and plot
+ Shannon diversity as effective number of species and plot
+ Functional diversity as effective number of species and plot
+ Pielou's evenness and plot
1. By *strata grouped and subregion* for each sampling year (using PSU data)
+ Mean abundance and plot
+ Mean biomass and plot
+ Richness and plot
+ Simpson diversity as effective number of species and plot
+ Shannon diversity as effective number of species and plot
+ Functional diversity as effective number of species and plot
+ Pielou's evenness and plot
1. By *NTMR* for each sampling year (using PSU data)
+ Mean abundance and plot
+ Mean biomass and plot
+ Richness as effective number of species and plot
+ Simpson diversity as effective number of species and plot
+ Shannon diversity as effective number of species and plot
+ Functional diversity as effective number of species and plot
+ Pielou's evenness and plot
1. Figure of the FKNMS coral reef tract with strata, subregions, and NTMR
1. Statistics
- Interpolate diversity for each year and strata using kriging
+ Figure. Spatial distribution of each matrices over time.
- Extract and interpolate the residuals of each index fitted against each other using GAM
+ temporal variable: YEAR
+ spatial variable: latitude, longitude
+ environmental variable: STRAT, habitat_cd, depth, bottom temperature
+ management variable: NTMR
- Calculate partial deviances
### Reef Visual Census Background
Reef fish community data used in this study were collected as part of the multi-agency Reef Visual Census (RVC) [Brandt et al., 2009](https://www.coris.noaa.gov/activities/fish_monitoring_protocol/). Fish communities were visually surveyed underwater annually in the mainland FKNMS (Lower Keys, Middle Keys and Upper Keys) from 1999 to 2012, and biennially from 2012 to 2016. The Dry Tortugas region was surveyed from 1999 to 2000 and biennially from 2004 to 2016.
The RVC uses a stationary point count method within a randomly selected 7.5 m radius circular plot with a 200m map grid from 1999 to 2012 and 100m map grid from 2014 to 2016 to optimize the observation of conspicuous and diurnally active reef fish, specifically economically and ecologically important reef fish species [Bohnsack and Bannerot, 1986](https://docs.lib.noaa.gov/noaa_documents/NMFS/TR_NMFS/TR_NMFS_41.pdf).
### Objective
To analyze and compare changes in species richness, Simpson diversity, Shannon diversity and functional diversity in the Florida Keys National Marine Sanctuary (FKNMS) to reveal changes in temporal and spatial variability from 1999 – 2016. The indices were assessed throughout the Florida Keys, between the upper and lower keys, between habitat types, and for different levels of management (Ecological Reserves (ER), Sanctuary Preservations Areas (SPA), and Special Use/Research Only Areas (SU/RO)).
## Diversity indicse as effective number of species
All diversity indices were computed as effective number of species. Effective number of species is the number of equally abundance species needed to produce the observed value of a diversity index (Jost, 2006; Jost et al., 2010; MacArthur, 1965). Jost, 2006 refers to these as true measures of diversity, where prior to the conversion the diversity indices are simply measures of entropy.
- Species Richness is the number of species in a habitat sampled
$Richness = \sum_{i=1}^S p_i^0$
- Simpson diversity measures the probability that two individuals randomly selected from a sample will belong to different species.
$Simpson = 1 - \sum_{i=1}^S p_i^2$
- Shannon diveristy is a measure of entropy, it is the uncertainty in the species identity of a sample
$Shannon = - \sum_{i=1}^S p_i \log_b p_i$
- Functional diversity (Rao's Q) is a measure of pairwise functional differences between species weighted by their relative abundances
$Rao Q = \sum_{i=1}^S-1 \sum_{j=i+1}^S d_i p_i p_j$
```{r setup, include= F}
#ln -s ~/Dropbox/big_csv big_csv - write in terminal window to link to 'big_csv' folder
#rm(list = ls())
#install.packages("rlang")
#update.packages("rlang")
library(devtools)
library(ape) #read.tree, as.phylo
library(clue) #cl_consensus, cl_ultrametric, cl_dissimilarity,cl_ultrametric
library(cowplot) #get_legend
#devtools::install_version("gridSVG", version="1.6-0")
devtools::install_github("timelyportfolio/d3treeR")
library(d3treeR) #d3treeR interactive traitmap
library(devtools) #install_github
library(FD) #gowdis
library(fpc) #pamk
install.packages("ggplot2",repos = c("http://rstudio.org/_packages", "http://cran.rstudio.com"))
library(ggplot2) #ggplot
library(grid)
library(gridExtra) #grid.arrange
library(htmlwidgets) #save interactive treemap and pie chart
library(lattice)
library(mgcv) #gam
library(parallel) #clusterEvalQ,clusterExport,detectCores,makeCluster,parLapply
library(plotrix) #std.error
library(purrr) #map
library(readr) #saveRDS, read_rds, readRDS
library(reshape2) #melt
devtools::install_github('jeremiaheb/rvc')
library(rvc) #getPSUAbundance, getStrataAbundance, getDomainAbundance
library(tidyverse) #select, filter, mutate, group_by, summarize
library(treemap) #treemap
library(vegan) #spec, diversity, richness
library(webshot) #screenshot of interactive treemap and pie chart
map = purrr::map # override maps::map
select = dplyr::select #override MASS::select
group_by = dplyr::group_by #override plotly::group_by
summarise = dplyr::summarise #override plotly::summarise
```
## Fetch the RVC data from
[NOAA's Southeast Fisheries Science Center server](https://grunt.sefsc.noaa.gov/rvc_analysis20/) using the [RVC package](https://github.com/jeremiaheb/rvc)
- Fetched weighted abundance and biomass data by domain, strata, and primary sampling units
#### Sample Data Variables
- PRIMARY_SAMPLE_UNIT: A code indicating the primary sample unit in which a sample was collected.
- YEAR: A number indicating the calendar year.
- MONTH: A number indicating the month of the year.
- DAY: A number indicating the day of the month (EST).
- STATION_NR: A number indicating the secondary sampling unit within a given primary sample unit.
- LAT_DEGREES: Latitude of secondary sampling unit in decimal degrees).
- LON_DEGREES: Longitude of secondary sampling unit in decimal degrees).
- DEPTH: Average depth, in meters, of secondary sampling unit).
- UNDERWATER_VISIBILITY: visibility, in meters, at secondary sampling unit.
- MAPGRID_NR: A number indicating the primary sample unit.
- HABITAT_CD: A code indicating the habitat type.
- ZONE_NR: A code indicating the distance offshore:
+ 1 - Inshore
+ 2 - Midchannel
+ 3 - Offshore
+ 4 - Fore-reef
- SUBREGION_NR: A number indicating the subregion.
- MPA_NR: A number identifying the marine protected area in which the sample was collected. Zero indicates unprotected status)
- SPECIES_NR: A number indicating the species for a sample
- SPECIES_CD: A code indicating the species for a sample. Consists of the first three letters of the generic name and the first four of the specific name
- LEN: The length, in cm, of a sample.
- NUM: The number of individuals of a given species and length observed in a secondary sampling unit
- TIME_SEEN: A number indicating when, during sampling, an individual was observed. 1: In the first five minutes, 2: From 5-10 minutes, 3: After 10 minutes.
- PROT: A boolean value indicating whether a sample was in a protected area or not
+ 1 - protected area
+ 0 - not protected
- STRAT: A code indicating the stratum in which a sample was taken. Differs by region.
+ FMLR
+ FSLR
+ HRRF
+ INPR
+ MCPR
+ OFPR
- REGION: A code indicating the region in which a sample was taken.
+ FLA KEYS (florida keys)
+ DRY TORT (dry tortugas)
#### Stratum Data Variables
- REGION
- YEAR
- PROT
- STRAT
- NTOT: The number of possible primary sample units for a given year, region, stratum, and protected status
- GRID_SIZE: The length (in meters) to a side of a primary sample unit for a given year, region, stratum, and protected status.
#### Taxonomic Data Variables
- SPECIES_CD
- FAMILY
- SCINAME
- COMNAME
- LC: Minimum length at capture, in centimeters
- LM: Median length at maturity, in centimeters.
- WLEN_A: The linear coefficient of the allometric growth equation in grams per millimeter (g/mm)
- WLEN_B: The exponential coefficient of the allometric growth equation
#### Benthic Data Variables
- REGION: A code indicating the region.
- YEAR: A number indicating the calendar year.
- PRIMARY_SAMPLE_UNIT: A code indicating the primary sample unit in which a sample was collected.
- STATION_NR: A number indicating the secondary sampling unit within a given primary sample unit.
- DEPTH: Average depth, in meters, of secondary sampling unit.
- MAX_HARD_RELIEF: The maximum height, in meters, of hard relief (e.g. hard corals, rock).
- MAX_SOFT_RELIEF: The maximum height, in meters, of soft relief (e.g. soft corals, sponges).
- AVG_HARD_RELIEF: The average height, in meters, of hard relief.
- HARD_REL_PCT_0: Percentage of hard relief less than 0.2 meters.
- HARD_REL_PCT_1: Percentage of hard relief between 0.2 and 0.5 meters.
- HARD_REL_PCT_2: Percentage of hard relief between 0.5 and 1.0 meters.
- HARD_REL_PCT_3: Percentage of hard relief between 1.0 and 1.5 meters.
- HARD_REL_PCT_4: Percentage of hard relief greater than 1.5 meters.
- PCT_SAND: Percentage of abiotic cover that is sand.
- PCT_HARD_BOTTOM: Percentage of abiotic cover that is hard bottom.
- PCT_RUBBLE: Percentage of abiotic cover that is rubble.
- PCT_CORAL: Percentage of biotic hardbottom that is coral.
- PCT_OCTO: Percentage of biotic hardbottom that is octocoral.
- PCT_SPONGE: Percentage of biotic hardbottom that is sponge.
#### Function: getDomainDensity
- YEAR
- REGION
- SPECIES_CD
- density: Domain-wide mean density for a stratified random survey
- var: Variance in average density per secondary sampling unit
- n: Number of primary sampling units sampled
- nm: Number of secondary sampling units sampled
- N: Number of total possible primary sample units
- NM: Number of possible secondary sampling units
- length_class: The length class or bin. Only present if length_bins is not NULL. The notation, [lower, upper), is inclusive of the lower bound, but exclusive of the upper bound
- protected_status: The protected status. Only present if merge_protected is FALSE
#### Florida Keys Strata
1. FSLR - Forereef Shallow Linear Reef (<6m)
2. FMLR - Forereef Midchannel Linear Reef (6-18m)
3. FDLR - Forereef Deep Linear Reef (18-33m)
4. INPR - Inshore patch reef
5. MCPR - Midchannel Patch Reef
6. OFPR - Offshore Patch Reef
7. HRRF - High Relief Reef (Spur and Groove)
```{r pull data}
spp_list = read_csv("Data/spp_list.csv")
fk1999<- getRvcData(1999, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk1999$taxonomic_data$SPECIES_CD
psu_abunfk1999 <- getPSUAbundance(fk1999, spp_list, merge_protected = F)
write_csv(psu_abunfk1999, 'Data/psu_abunfk1999.csv') #1999
fk2000<- getRvcData(2000, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2000$taxonomic_data$SPECIES_CD
psu_abunfk2000 <- getPSUAbundance(fk2000, spp_list, merge_protected = F)
write_csv(psu_abunfk2000, 'Data/psu_abunfk2000.csv') #2000
fk2001<- getRvcData(2001, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2001$taxonomic_data$SPECIES_CD
psu_abunfk2001 <- getPSUAbundance(fk2001, spp_list, merge_protected = F)
write_csv(psu_abunfk2001, 'Data/psu_abunfk2001.csv') #2001
fk2002<- getRvcData(2002, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2002$taxonomic_data$SPECIES_CD
psu_abunfk2002 <- getPSUAbundance(fk2002, spp_list, merge_protected = F)
write_csv(psu_abunfk2002, 'Data/psu_abunfk2002.csv') #2002
fk2003<- getRvcData(2003, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2003$taxonomic_data$SPECIES_CD
psu_abunfk2003 <- getPSUAbundance(fk2003, spp_list, merge_protected = F)
write_csv(psu_abunfk2003, 'Data/psu_abunfk2003.csv') #2003
fk2004<- getRvcData(2004, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2004$taxonomic_data$SPECIES_CD
psu_abunfk2004 <- getPSUAbundance(fk2004, spp_list, merge_protected = F)
write_csv(psu_abunfk2004, 'Data/psu_abunfk2004.csv') #2004
fk2005<- getRvcData(2005, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2005$taxonomic_data$SPECIES_CD
psu_abunfk2005 <- getPSUAbundance(fk2005, spp_list, merge_protected = F)
write_csv(psu_abunfk2005, 'Data/psu_abunfk2005.csv') #2005
fk2006<- getRvcData(2006, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2006$taxonomic_data$SPECIES_CD
psu_abunfk2006 <- getPSUAbundance(fk2006, spp_list, merge_protected = F)
write_csv(psu_abunfk2006, 'Data/psu_abunfk2006.csv') #2006
fk2007<- getRvcData(2007, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2007$taxonomic_data$SPECIES_CD
psu_abunfk2007 <- getPSUAbundance(fk2007, spp_list, merge_protected = F)
write_csv(psu_abunfk2007, 'Data/psu_abunfk2007.csv') #2007
fk2008<- getRvcData(2008, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2008$taxonomic_data$SPECIES_CD
psu_abunfk2008 <- getPSUAbundance(fk2008, spp_list, merge_protected = F)
write_csv(psu_abunfk2008, 'Data/psu_abunfk2008.csv') #2008
fk2009<- getRvcData(2009, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2009$taxonomic_data$SPECIES_CD
psu_abunfk2009 <- getPSUAbundance(fk2009, spp_list, merge_protected = F)
write_csv(psu_abunfk2009, 'Data/psu_abunfk2009.csv') #2009
fk2010<- getRvcData(2010, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2010$taxonomic_data$SPECIES_CD
psu_abunfk2010 <- getPSUAbundance(fk2010, spp_list, merge_protected = F)
write_csv(psu_abunfk2010, 'Data/psu_abunfk2010.csv') #2010
fk2011<- getRvcData(2011, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2011$taxonomic_data$SPECIES_CD
psu_abunfk2011 <- getPSUAbundance(fk2011, spp_list, merge_protected = F)
write_csv(psu_abunfk2011, 'Data/psu_abunfk2011.csv') #2011
fk2012<- getRvcData(2012, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2012$taxonomic_data$SPECIES_CD
psu_abunfk2012 <- getPSUAbundance(fk2012, spp_list, merge_protected = F)
write_csv(psu_abunfk2012, 'Data/psu_abunfk2012.csv') #2012
fk2014<- getRvcData(2014, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2014$taxonomic_data$SPECIES_CD
psu_abunfk2014 <- getPSUAbundance(fk2014, spp_list, merge_protected = F)
write_csv(psu_abunfk2014, 'Data/psu_abunfk2014.csv') #2014
fk2016<- getRvcData(2016, "FLA KEYS", server = 'https://www.sefsc.noaa.gov/rvc_analysis20/')
spp_list<- fk2016$taxonomic_data$SPECIES_CD
psu_abunfk2016 <- getPSUAbundance(fk2016, spp_list, merge_protected = F)
write_csv(psu_abunfk2016, 'Data/psu_abunfk2016.csv') #2016
fk2018<- getRvcData(2018, "FLA KEYS")
spp_list<- fk2018$taxonomic_data$SPECIES_CD #402 species
psu_abunfk2018 <- getPSUAbundance(fk2018, spp_list, merge_protected = F)
write_csv(psu_abunfk2018, 'Data/psu_abunfk2018.csv') #2016
fk2018 = getRvcData(2018, "FLA KEYS")
fk2018$sample_data = psu_abunfk2018
fk2018$stratum_data$YEAR = 2018
psu_abunfk2018 = getPSUAbundance(fk2018, spp_list$spp_list)
write_csv(psu_abunfk2018, "Data/psu_abunfk2018.csv") #2018
```
```{r bind data}
##FK abundance psu
cat("bind all csv's\n") #concatenate and print - character string naming the file to print to
d = data_frame()
for (f in list.files('Data/FK_PSU_Abundance_Data/', pattern="*.csv", full.names=T)){
cat(' ', f,'\n')
d_f = read_csv(
f, #path to a file
progress=F, #progress: Display a progress bar
trim_ws=T, #trim_ws: leading and trailing whitespace are trimmed
col_types = cols(
protected_status = col_character())) #column specification - must contain one column specification for each column
d = bind_rows(d, d_f)
}
write_csv(d, 'Data/psu_fk_abun_1999-2018.csv')
```
### Florida Keys Primary Sampling Unit
```{r clean psu abundance data}
#read in data
psu_fk_abun <- read_csv("Data/psu_fk_abun_1999-2018.csv",
col_types = cols(protected_status = col_character()))
#dim(psu_fk_abun) #3,697,914 x 10
length(unique(psu_fk_abun$SPECIES_CD)) #401 species
#remove species not identified in species level and protected status all
psu_fk_abun_no_spp = psu_fk_abun %>%
filter(!stringr::str_detect(SPECIES_CD, 'SPE\\.$')) %>% #370 species
filter(!abundance == "0") %>% #remove species with abundance = 0 #319 species
filter(stringr::str_detect(protected_status, 'all')) #remove duplicates of 'all'
#dim(psu_fk_abun_no_spp) #204,342 x 10
psu_abun_sum <- psu_fk_abun_no_spp %>%
group_by(YEAR, PRIMARY_SAMPLE_UNIT, STRAT) %>%
summarize(abundance_sum = sum(abundance)) %>% #sum the abundance values and remove any PSU's with no species
filter(!abundance_sum == "0") %>% #redundant since already removed species = 0 above
filter(!abundance_sum <= 1) %>% #remove PSU's with <1 species in order to calculate diversity [2006,602U INPR], [2016, 1010U, INPR], [2018, 1004U, INPR], [2018, 1013U, INPR]
filter(!abundance_sum > 100000 ) #outlier 2001 PSU 222U HRRF abundance 100,229 counts
#dim(psu_abun_sum) #5269*4
#remove follow PSU [2006,602U INPR], [2016, 1010U, INPR], [2018, 1004U, INPR], [2018, 1013U, INPR]
psu_fk_abun_no_spp = psu_fk_abun_no_spp[!(
psu_fk_abun_no_spp$YEAR == "2006" & psu_fk_abun_no_spp$PRIMARY_SAMPLE_UNIT == "602U" |
psu_fk_abun_no_spp$YEAR == "2016" & psu_fk_abun_no_spp$PRIMARY_SAMPLE_UNIT == "1010U" |
#psu_fk_abun_no_spp$YEAR == "2018" & psu_fk_abun_no_spp$PRIMARY_SAMPLE_UNIT == "1004U" |
#psu_fk_abun_no_spp$YEAR == "2018" & psu_fk_abun_no_spp$PRIMARY_SAMPLE_UNIT == "1013U" |
psu_fk_abun_no_spp$YEAR == "2001" & psu_fk_abun_no_spp$PRIMARY_SAMPLE_UNIT == "222U"),]
dim(psu_fk_abun_no_spp) #204280*4
write_csv(psu_fk_abun_no_spp, "Data/psu_fk_abun_no_spp.csv")
length(unique(psu_fk_abun_no_spp$SPECIES_CD)) #319 species
species_list = as.data.frame(unique(psu_fk_abun_no_spp$SPECIES_CD))
write_csv(species_list, "Data/species_list.csv")
length(unique(psu_fk_abun_no_spp$PRIMARY_SAMPLE_UNIT)) #1671 sampling events
RVCdata_FK = read_rds('Data/RVCdata_FK.rds')
family = RVCdata_FK$taxonomic_data
psu_family = left_join(psu_fk_abun_no_spp, family, by= "SPECIES_CD")
psu_family_group <- psu_family %>%
group_by(FAMILY) %>%
summarize(abundance_sum = sum(abundance)) %>%
filter(abundance_sum != "0") %>%
mutate(fam_percent = (abundance_sum/sum(abundance_sum))*100) %>%
arrange(desc(fam_percent))
write_csv(psu_family_group, "psu_family_group.csv")
#FAMILY abundance_sum fam_percent
# Family Name abundance sum percent
# 1 Labridae 406606. 20.7%
# 2 Pomacentridae 343083. 17.4%
# 3 Haemulidae 332576. 16.9%
# 4 Gobiidae 201174. 10.2%
# 5 Scaridae 180292. 9.17%
psu_common <- psu_family %>%
group_by(COMNAME) %>%
summarize(abundance_sum = sum(abundance)) %>%
filter(abundance_sum != "0") %>% #removes 32 species
mutate(com_percent = (abundance_sum/sum(abundance_sum))*100) %>%
arrange(desc(com_percent))
write_csv(psu_common, "psu_common.csv")
#COMNAME abundance_sum com_percent
# 1 Bicolor Damselfish 226261. 11.5%
# 2 Bluehead 212810. 10.8%
# 3 Masked Goby 174525. 8.87%
psu_sciname <- psu_family %>%
group_by(SCINAME) %>%
summarize(abundance_sum = sum(abundance)) %>%
filter(abundance_sum != "0") %>% #removes 32 species
mutate(com_percent = (abundance_sum/sum(abundance_sum))*100) %>%
arrange(desc(com_percent))
```
## Functional distance trait based matrix (from Lefcheck et al., 2014 ChessMap.Rmd)
Gowdis computes the Gower (1971) similarity coefficient exactly as described by Podani (1999), then converts it to a dissimilarity coefficient by using D = 1 - S
```{r Functional distance matrix, eval = F}
knitr::opts_chunk$set(echo = TRUE)
if (!file.exists("Data/func_dist_rds")){
trait_matrix = read_csv('Data/species_trait_matrix_319_spp.csv') #319 species
trait_matrix_scientific_name = trait_matrix %>%
as.tibble() %>%
mutate(
SPECIES_CD = toupper(as.character(SPECIES_CD))) %>%
arrange(SPECIES_CD)%>%
select(SPECIES_CD, Maxlength, Trophic_level, Trophic_group, Water_column, Diel_activity, Substrate_type, Complexity, Gregariousness) %>% #348*9
group_by(
SPECIES_CD, Maxlength, Trophic_level, Trophic_group, Water_column, Diel_activity, Substrate_type, Complexity, Gregariousness) %>%
#summarize(n = n()) %>%
#select(-n) %>%
ungroup() %>%
mutate(
# ordinal traits
Complexity = ordered(Complexity, levels=c("Low","Medium","High")),
Gregariousness = ordered(Gregariousness, levels=c("1","2","3"))) %>%
as.data.frame()
#Set species names as row.names and remove extra columns
rownames(trait_matrix_scientific_name)=trait_matrix_scientific_name$SPECIES_CD
#Calculate Gower distances. Variables have equal weight.
traits.dist = gowdis(trait_matrix_scientific_name, ord="podani")
trait_matrix_common = trait_matrix %>%
as.tibble() %>%
mutate(
Common_name = toupper(as.character(Common_name))) %>%
arrange(Common_name)%>%
select(Common_name, Maxlength, Trophic_level, Trophic_group, Water_column, Diel_activity, Substrate_type, Complexity, Gregariousness) %>% #348*9
group_by(
Common_name, Maxlength, Trophic_level, Trophic_group, Water_column, Diel_activity, Substrate_type, Complexity, Gregariousness) %>%
#summarize(n = n()) %>%
#select(-n) %>%
ungroup() %>%
mutate(
# ordinal traits
Complexity = ordered(Complexity, levels=c("Low","Medium","High")),
Gregariousness = ordered(Gregariousness, levels=c("1","2","3"))) %>%
as.data.frame()
#Set species names as row.names and remove extra columns
rownames(trait_matrix_common)=trait_matrix_common$Common_name
#Calculate Gower distances. Variables have equal weight.
traits.dist.common = gowdis(trait_matrix_common, ord="podani")
#Use clustering method to produce ultrametric dendrogram because values of Rao's Q can be maximized when fewer than the max number of functional types are present unless distances are ultramtetric
#to account for sensitivity in clustering use multiple algorithms (Mouchet et al., 2008)
tree_methods = c("single","complete","average","mcquitty","ward.D") #average is best clustering method
trees=lapply(tree_methods, function(i) hclust(traits.dist, method=i))
par(mfrow=c(3,2))
for(i in 1:length(trees)) {plot(trees[[i]])} #plots the 5 different kinds of trees
#convert trees to ultrametric
trees.ultra= lapply(trees,function(i) cl_ultrametric(as.hclust(i)))
#Plot each tree
par(mfrow=c(3,2))
for (i in 1:length(trees.ultra)) {plot(trees.ultra[[i]])} #plots the 5 different kinds of trees
#Build the consensus tree (Mouchet et al 2008 Oikos)
ensemble.trees=cl_ensemble(list=trees) #list of clusterings
class(ensemble.trees)
consensus.tree=cl_consensus(ensemble.trees) #synthesizes the information in the elements of a cluster ensemble into a single clustering
par(mar=c(1,1,1,1))
plot(consensus.tree, horiz=T)
#Calculate dissimilarity values for each tree using 2-norm (Merigot et al 2010 Ecology) to determine which tree best preserves orignial distances
#spectral norm (2-norm) of the differences of the ultrametrics
all.trees=c(trees.ultra,consensus.tree[1])
names(all.trees)=c(tree_methods,"consensus")
(trees.dissim=lapply(all.trees,function(i) cl_dissimilarity(i,traits.dist,method="spectral")))
#Cross-dissimilarities using spectral ultrametric distance:
#Single = 57.80006
#complete = 100.0702
#average = 13.57471
#mcquitty = 34.08532
#ward.D = 2759.852
#consensus = 1039.107
#Identify best tree and isolate
trees.dissim2=do.call(rbind,trees.dissim)
min.tree=which.min(trees.dissim2) #average
names(all.trees)[min.tree]
func.dist=all.trees[names(all.trees)==names(all.trees)[min.tree]][[1]]
#Confirm lowest 2-norm value, spectral norm (2-norm) of the differences if the ultrametrics
cl_dissimilarity(func.dist,traits.dist,method="spectral") #Cross-dissimilarities using spectral ultrametric distance: 13.57471
#Scale by the max value so that all values are between 0-1
func.dist=func.dist/max(func.dist)
saveRDS(func.dist, "Data/func_dist_rds")
} else { #read data
func.dist = read_rds("Data/func_dist_rds")
}
func_dist_common = read_rds("Data/func_dist_common_name_rds")
func_dist_phy_common = as.phylo(as.hclust(func_dist_common))
#Plot the best tree - average
#removes 298/348 species
pdf("functional_diversity/functional_dendrogram_2.pdf", width = 7, height = 10)
sup = drop.tip(func_dist_phy_common, sample(func_dist_phy_common$tip.label)[1:298])
par(mfrow=c(1,1))
plot(sup, horiz=TRUE, main = "Functional Dendrogram", cex = 0.5, label.offset=0.025, edge.width = 1, cex.main = 1.5)
dev.off()
#removes 150/348 species 2 pages
pdf("functional_diversity/functional_dendrogram_2.pdf", width = 7, height = 20)
sup = drop.tip(func_dist_phy_common, sample(func_dist_phy_common$tip.label)[1:150])
par(mfrow=c(1,1))
plot(sup, horiz=TRUE, main = "Functional Dendrogram", cex = 0.5, label.offset=0.025, edge.width = 1, cex.main = 1.5)
dev.off()
#with scale
pdf("functional_diversity/functional_dendrogram.pdf", width = 8.5, height = 70)
#par(mar=c(0,0,0,0)) #number of lines of margins for bottom, left, top, right
par(pin=c(4.5,65)) #plot dimensions (width, height)
plot(func_dist_common, horiz=TRUE, main = "Functional Dendrogram", cex = 1, cex.main = 2, cex.lab = 1)
dev.off()
tiff("functional_diversity/functional_dendrogram.tiff", width = 8.5, height = 70)
#par(mar=c(0,0,0,0)) #number of lines of margins for bottom, left, top, right
par(pin=c(4.5,65)) #plot dimensions (width, height)
plot(func_dist_common, horiz=TRUE, main = "Functional Dendrogram", cex = 1, cex.main = 2, cex.lab = 1)
dev.off()
#with scale
tiff("fd.tiff", width = 8.5, height = 70, units = "in", res = 300)
par(pin=c(3.5,65)) #plot dimensions (width, height)
plot(func_dist_common, horiz=TRUE, main = "Functional Dendrogram", cex = 1, cex.main = 2, cex.lab = 1)
dev.off()
#Plot the best tree - average
pdf("functional_diversity/functional_dendrogram.pdf", width = 7, height = 80)
par(mfrow=c(1,1)) #nc-by-nr array
par(mar=c(2,1,0,2)) #number of lines of margins for bottom, left, top, right
par(pin=c(5,70)) #plot dimensions (width, height)
plot(func.dist, horiz=TRUE, main = "Functional Dendrogram", cex = 1, cex.main = 1.5, cex.lab = 1)
dev.off()
#Plot the best tree - average
#removes 260/348 species
pdf("functional_dendrogram.pdf", width = 7, height = 10)
sup = drop.tip(func.dist, sample(func.dist$tip.label)[1:260])
par(mfrow=c(1,1))
plot(sup, horiz=TRUE, main = "Functional Dendrogram", cex = 0.5, label.offset=0.025, edge.width = 1, cex.main = 2)
dev.off()
pdf("functional_dendrogram.pdf", width = 7, height = 70)
par(mfrow=c(1,1))
plot(func.dist, horiz=TRUE, main = "Functional Dendrogram", cex = 0.5, label.offset=0.025, edge.width = 1, cex.main = 2) #cex.lab = 0.5
dev.off()
#Phylogenetic tree with 348 tips and 347 internal nodes.
func.dist.phy = as.phylo(as.hclust(func.dist))
#Write newick tree
write.tree(func.dist.phy, "functional_diversity/functional_dendrogram.nwk")
#write.nexus(func.dist.phy, "functional_diversity/functional_dendrogram.nex")
tree <- read.tree("functional_diversity/functional_dendrogram.nwk")
# List of 4
# $ edge : int [1:694, 1:2]
# $ Nnode : int 347
# $ tip.label : chr [1:348]
# $ edge.length: num
# - attr(*, "class")= chr "phylo"
# - attr(*, "order")= chr "cladewise"
# Phylogenetic tree with 348 tips and 347 internal nodes.
# Tip labels:
# KYP_SECT, ALE_CILI, ELO_SAUR, HAR_JAGU, CEN_UNDE, TYL_CROC, ...
# Rooted; includes branch lengths.
plot(tree, label.offset=0.2, edge.width = 2, type = "cladogram")
nodelabels() #add node numbers
tiplabels() #add tip numbers
ggtree(tree, branch.length = T) +
ggtitle("Functional Dendogram") +
geom_tiplab()+
geom_text(aes(x = branch, label=branch.length), vjust = -.5) +
theme_tree2()
ggtree(tree, layout= "circular") +
ggtitle("Functional Dendogram") +
geom_tiplab(size = 1, aes(angle=angle))+
theme_tree2()
# transformed to a tidy data.frame by fortify method
tree_data <- fortify(tree) #node; parent; branch.length; x; y; label; isTip; branch; angle
head(tree_data)
#Visualize species' differences in multivariate trait space
#Perform k-means clustering with no a priori specification for k
traits.kclus= pamk(traits.dist, krange=2:10)
traits.kclus.common= pamk(traits.dist.common, krange=2:10)
#krange: integer vector. Numbers of clusters which are to be compared by the average silhouette width criterion.
#traits.kclus$nc = 10
#traits.kclus$crit 0.0000000 0.2374706 0.2362513 0.2355555 0.2681756 0.2581352 0.2759547 0.2852216 0.3006077 0.3062123
# #Perform nonmetric multidimensional scaling (NMDS) on functional dendrogram
traits_nmds = metaMDS(traits.dist,k=traits.kclus$nc,trymax=20)
traits_nmds.common = metaMDS(traits.dist.common,k=traits.kclus.common$nc,trymax=300)
#k = Number of dimensions
#*** No convergence -- monoMDS stopping criteria:
#499: no. of iterations >= maxit
#1: stress ratio > sratmax
# Dimensions: 10
# Stress: 0.03545178
# Stress type 1, weak ties
# No convergent solutions - best solution after 500 tries
# Scaling: centring, PC rotation
# Species: scores missing
# #Plot in two dimensions - doesn't work
par(mar=c(4,4,1,1))
ordiplot(traits_nmds.common,type="n") #type="n"type="points"
#Assign colors to different groups
groups=levels(factor(traits.kclus.common$pamobject$clustering))
points.symbols=15:16
points.colors=c("firebrick3","cornflowerblue")
for(i in seq_along(groups)) {
points(traits_nmds.common$points[traits.kclus.common$pamobject$clustering==groups[i],],
pch=points.symbols[i],col=points.colors[i],cex=1.4) }
ordispider(traits_nmds.common,factor(traits.kclus.common$pamobject$clustering),label=F)
ordihull(traits_nmds.common,factor(traits.kclus.common$pamobject$clustering),lty="dotted")
orditorp(traits_nmds.common,dis="sites",pcex=0,air=0.5,col="grey10",cex=0.8)
```
#Calculate Richness, Simpson and Shannon diversity
```{r psu biodiversity}
if(!file.exists("psu_div_rds")){
#read in psu abundance data
psu_fk_abun <- read_csv("Data/psu_fk_abun_no_spp.csv",
col_types = cols(
protected_status = col_character()))
#dim(psu_fk_abun) #198,409*10
#read in trait matrix
trait_matrix = read_csv('Data/species_trait_matrix_319_spp.csv')
#trait matrix needs to be alphabetically for FD code
trait_matrix = trait_matrix %>%
as_tibble() %>%
mutate(
SPECIES_CD = toupper(as.character(SPECIES_CD))) %>%
arrange(SPECIES_CD)
#compute diversity indices by PSU
psu_diversity = psu_fk_abun %>%
select(YEAR, PRIMARY_SAMPLE_UNIT,STRAT,PROT,SPECIES_CD, abundance) %>% #tibble: 198409 x 6
group_by(YEAR, PRIMARY_SAMPLE_UNIT, STRAT, PROT) %>%
nest(-YEAR, -PRIMARY_SAMPLE_UNIT, -STRAT, -PROT)
psu_diversity = psu_diversity %>%
mutate(
data_wide = map(data, function(x)
full_join(x, trait_matrix %>% select(SPECIES_CD), by='SPECIES_CD') %>%
mutate(abundance = ifelse(is.na(abundance), 0, abundance)) %>%
spread(SPECIES_CD, abundance, fill =0)),
data_wide = map(data, ~ spread(data=.x, SPECIES_CD, abundance, fill =0)),
richness = map( #species richness
data_wide,
function(x) specnumber(x)),
simpson = map( #simpson diversity as effective number of species
data_wide,
function(x) 1/(1 - diversity(x, index = 'simpson'))),
shannon = map( #shannon diversity as effective number of species
data_wide,
function(x) exp(diversity(x, index = 'shannon')))) %>%
unnest(richness, simpson, shannon)
saveRDS(psu_diversity, "Data/psu_div_rds")
} else { #read data
psu_div = read_rds("Data/psu_div_rds")
}
```
# Calculate Functional Diversity and Evenness
```{r biodiversity 2.0}
func.dist = read_rds("Data/func_dist_rds")
#read in trait matrix
traits = read.csv('Data/species_trait_matrix_319_spp.csv')
#Set rownames on traits and remove other info
rownames(traits) <- traits$SPECIES_CD
traits <- traits[, -c(1:4)]
#Convert rownames to all caps
rownames(traits) <- toupper(rownames(traits))
psu_fk_abun <- read_csv("Data/psu_fk_abun_no_spp.csv",
col_types = cols(
protected_status = col_character()))
abund = psu_fk_abun %>%
select(YEAR, PRIMARY_SAMPLE_UNIT,STRAT,PROT, SPECIES_CD, abundance) %>%
arrange(YEAR, PRIMARY_SAMPLE_UNIT, STRAT, PROT)
#204,280 * 6
# Cast abundance longways (species as columns)
abundmat = spread(abund, SPECIES_CD, abundance, fill = 0)
#dim(abundmat) #5270 323
# What is up with these species not being in the trait matrix??
checkthese = colnames(abundmat)[!colnames(abundmat) %in% rownames(traits)]
# Subset species whose names only appear in traits
abundmat = abundmat[colnames(abundmat) %in% rownames(traits)]
#dim(abundmat) #5,270 319
# Drop communities with no species (roughly 500 sites)
abundmat <- abundmat[!rowSums(abundmat) == 0,]
#dim(abundmat) #5,270 319
abundmat <- abundmat[!rowSums(abundmat) == 1,]
#dim(abundmat) #5270 319
#Calculate relative values for community matrix
rel.mat=abundmat/apply(abundmat,1,sum)
#Compute species diversity
species.dist=matrix(1,ncol(abundmat),ncol(abundmat))-diag(rep(1,ncol(abundmat)))
species.div=1/(1-apply(rel.mat,1,function(x) t(x) %*% species.dist %*% x))
#Compute evenness (as in Jost 2010 Diversity)
evenness=log(species.div)/log(rowSums(abundmat>0))
#Ensure that all evenness calculations are not >1 (bug)
func.div=1/(1-apply(rel.mat,1,function(x) t(x) %*% as.matrix(func.dist) %*% x))
#Bind all to the original dataframe
diversity = cbind(evenness,species.div,func.div)
diversity = as.tibble(diversity)
psu_diversity = psu_diversity %>%
select(YEAR, PRIMARY_SAMPLE_UNIT, STRAT, PROT, richness, simpson, shannon)%>%
arrange(YEAR, PRIMARY_SAMPLE_UNIT, STRAT, PROT)
abund_sum = psu_fk_abun %>%
select(YEAR, PRIMARY_SAMPLE_UNIT,STRAT,PROT, SPECIES_CD, abundance) %>%
arrange(YEAR, PRIMARY_SAMPLE_UNIT, STRAT, PROT)%>%
group_by(YEAR, PRIMARY_SAMPLE_UNIT, STRAT, PROT)%>%
summarize(abundance_sum = sum(abundance))%>%
select(abundance_sum)
RVC_biodiversity_calculated = bind_cols(abund_sum, psu_diversity,diversity)
write_csv(RVC_biodiversity_calculated, "Data/RVC_biodiversity_calculated.csv")
```
## Trait matrix visualization
[http://jkunst.com/r/pokemon-visualize-em-all/]
[https://d3js.org/]
[http://www.buildingwidgets.com/blog/2015/7/22/week-29-d3treer-v2]
```{r trait visualization}
trait_matrix = read_csv('Data/species_trait_matrix_319_spp.csv')
trait_matrix_treemap = trait_matrix %>%
select(Common_name, Maxlength, Trophic_level, Trophic_group, Water_column,Diel_activity,Substrate_type,Complexity, Gregariousness) %>%
group_by(Maxlength,
Trophic_level,
Trophic_group,
Water_column,
Diel_activity,
Substrate_type,
Complexity,
Gregariousness) %>%
summarise(n = n())%>%
ungroup() %>%
as.data.frame()
treemap2 =
d3treeR::d3tree2(
treemap(
dtf = trait_matrix_treemap,
index = c("Trophic_group", "Diel_activity", "Substrate_type", "Trophic_level", "Water_column","Maxlength","Complexity","Gregariousness"),
vSize = "n",
vColor = "Trophic_group",
type = "index"),
#title = "Reef Fish Traits",
#fontsize.title = 14,
#algorithm = "squarified"
rootname = "Species Traits")
treemap2
htm = "./htmlwidget_treemap2.html"
saveWidget(treemap2, htm)
png = "./htmlwidget_treemap2.png"
webshot(htm, png)
trait_matrix_treemap3 = trait_matrix %>%
select(Common_name, Maxlength, Trophic_level, Trophic_group, Water_column,Diel_activity,Substrate_type,Complexity, Gregariousness) %>%
group_by(
Trophic_group,
Water_column,
Diel_activity,
Substrate_type
) %>%
summarise(n = n())%>%
ungroup() %>%
as.data.frame()
treemap3 =
d3treeR::d3tree2(
treemap(
dtf = trait_matrix_treemap3,
index = c("Trophic_group", "Diel_activity", "Substrate_type", "Water_column"),#"Trophic_level" #"Diel_activity", "Substrate_type", "Water_column", "Complexity", "Substrate_type", "Trophic_level"),
vSize = "n",
vColor = "Trophic_group",
type = "index"),
#title = "Reef Fish Traits",
#fontsize.title = 14,
#algorithm = "squarified"
rootname = "Species Traits")
```
## Plots
- create multiplot function from (https://stackoverflow.com/questions/24387376/r-weird-error-could-not-find-function-multiplot)
Questions
- Are diversity values and grouped strata related?
- Are diversity values and subregions related?
- Are diversity values and protection level related?
Group strata by: patch reef, forereef, and high relief
```{r Plot by strata grouped and year}
all_matrices_data = read_csv("Data/RVC_biodiversity_calculated.csv")
matrices_strat_grouped = all_matrices_data %>%
mutate(
STRAT_GROUPED = #group strata
ifelse(grepl("FMLR|FSLR|FDLR", STRAT), 'LINEAR_REEF',
ifelse(grepl("OFPR|MCPR|INPR", STRAT), 'PATCH_REEF',
ifelse(grepl('HRRF', STRAT), 'HIGH_RELIEF', "IDK")))) %>%
group_by(YEAR, STRAT_GROUPED) %>%
summarize( #calculate mean, sd, min, max, se
abundance_mean = mean(abundance_sum),
abundance_n = length(abundance_sum),
abundance_sd = sd(abundance_sum),
abundance_se = abundance_sd / sqrt(abundance_n),
abundance_min = min(abundance_sum),
abundance_max = max(abundance_sum),
richness_mean = mean(richness),
richness_n = length(richness),
richness_sd = sd(richness),
richness_se = richness_sd / sqrt(richness_n),
richness_min = min(richness),
richness_max = max(richness),
simpson_mean = mean(simpson),
simpson_n = length(simpson),
simpson_sd = sd(simpson),
simpson_se = simpson_sd / sqrt(simpson_n),
simpson_min = min(simpson),
simpson_max = max(simpson),
shannon_mean = mean(shannon),
func.div_mean = mean(func.div),
func.div_n = length(func.div),
func.div_sd = sd(func.div),
func.div_se = func.div_sd / sqrt(func.div_n),
func.div_min = min(func.div),
func.div_max = max(func.div),
evenness_mean = mean(evenness),
evenness_n = length(evenness),
evenness_sd = sd(evenness),
evenness_se = evenness_sd / sqrt(evenness_n),
evenness_min = min(evenness),
evenness_max = max(evenness))
write_csv(matrices_strat_grouped, "Data/matrices_strat_grouped.csv")
# by STRAT_GROUPED and YEAR
#abundance
ab_gs= ggplot(matrices_strat_grouped,aes(x=YEAR,y=abundance_mean, colour=STRAT_GROUPED, group=STRAT_GROUPED))+ #shape=STRAT
geom_line(aes(group=STRAT_GROUPED),lwd=1) +
geom_point(size=3) +
geom_errorbar(aes(ymax=abundance_mean+abundance_se,ymin=abundance_mean-abundance_se),width=0.1)+
labs(title= "A) Abundance", x="Year", y="Mean abundance", colour = "Strata")+
scale_colour_manual(labels=c("High reef", "Linear reef", "Patch reef"), values= c("red", "green", "blue"))+
scale_x_continuous(limits = c(1999, 2018),
breaks = c(1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011, 2012, 2013, 2014, 2015,2016,2017, 2018),
labels=c("","2000","","2002","","2004","","2006","","2008","","2010","","2012","","2014","","2016","","2018"))+
theme_bw()+
theme(
legend.position="none",
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
axis.title.x=element_text(size=12),
axis.title.y=element_text(size=12),
title=element_text(size=12))
ggsave(file="abundance_by_year_and_strata_grouped.pdf", path="Figures")
#richness
rich_gs= ggplot(matrices_strat_grouped,aes(x=YEAR,y=richness_mean, colour=STRAT_GROUPED, group=STRAT_GROUPED))+ #shape=STRAT
geom_line(aes(group=STRAT_GROUPED),lwd=1) +
geom_point(size=3) +
geom_errorbar(aes(ymin=richness_mean-richness_se, ymax=richness_mean+richness_se), width=.1)+
labs(title= "D) Richness", x="Year", y="Mean ENS", colour = "Strata")+
scale_colour_manual(labels=c("High reef", "Linear reef", "Patch reef"), values= c("red", "green", "blue"))+
scale_x_continuous(limits = c(1999, 2018),
breaks = c(1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011, 2012, 2013, 2014, 2015,2016,2017, 2018),
labels=c("","2000","","2002","","2004","","2006","","2008","","2010","","2012","","2014","","2016","","2018"))+
theme_bw()+
theme(
legend.position="none",
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
axis.title.x=element_text(size=12),
axis.title.y=element_text(size=12),
title=element_text(size=12))
ggsave(file="richness_by_year_and_strata_grouped.pdf", path="Figures")
#simpson
sim_gs= ggplot(matrices_strat_grouped,aes(x=YEAR,y=simpson_mean, colour=STRAT_GROUPED, group=STRAT_GROUPED))+ #shape=STRAT
geom_line(aes(group=STRAT_GROUPED),lwd=1) +
geom_point(size=3) +
geom_errorbar(aes(ymin=simpson_mean-simpson_se, ymax=simpson_mean+simpson_se), width=.1)+
labs(title= "E) Simpson", x="Year", y="Mean ENS", colour = "Strata")+
scale_colour_manual(labels=c("High reef", "Linear reef", "Patch reef"), values= c("red", "green", "blue"))+
scale_x_continuous(limits = c(1999, 2018),
breaks = c(1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011, 2012, 2013, 2014, 2015,2016,2017, 2018),
labels=c("","2000","","2002","","2004","","2006","","2008","","2010","","2012","","2014","","2016","","2018"))+
theme_bw()+
theme(
legend.position="none",