-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFishSizeTemperatureMainDocument_Public.Rmd
2174 lines (1652 loc) · 83.3 KB
/
FishSizeTemperatureMainDocument_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: "Changes in fish body sizes relate to temperature, but not all species shrink with warming"
author: "Asta Audzijonyte, Shane Richards, Julia Blanchard et al."
date: "22 March 2018"
output:
html_document:
code_folding: show
toc: yes
toc_float: yes
pdf_document:
toc:yes
---
This document is an electronic supplement to the publication "Fish body sizes change with temperature, but not all species shrink with warming" by Audzijonyte A, Richards SA, Stuart-Smith RD, Pecl G, Edgar GJ, Barrett NS, Payne N, Blanchard JL, Nature Ecology and Evolution (https://www.nature.com/articles/s41559-020-1171-0).
**If you want to use the dataset for further research or publications it would be appropriate to contact Rick Stuart-Smith, Graham Edgar and Neville Barret who are behind this massive effort of long-term data collection**
To run the code make sure all the libraries listed in the first chunk are installed
### Load libraries
```{r warning=FALSE, message=FALSE, echo=FALSE, eval= T}
rm(list = ls()) # clear memory
library(tidyverse)
library(maps)
library(mapdata)
library(rstan)
library(ggplot2)
library(ggmap)
library(reshape)
library(lmodel2)
library(cowplot)
library(weights)
library(rgdal)
```
### Load datafiles
```{r warning=FALSE, message=FALSE, eval=T, echo=FALSE}
#Main datafile of fish sizes after removing outliers and rare species (335 species in the dataset)
load(file = "inputs/fish_data.RData") #the data file is called main_data
#check that we have 335 species
length(unique(main_data$TAXONOMIC_NAME))
```
### Extended Data Fig1: map data and sites
```{r warning=FALSE, message=FALSE, echo = F, eval = T, fig.width=10, fig.height=6}
# Here you can explore all survey sites in the dataset, but plotting them AKES A LONG TIME!!!
#ggmap(australia, extent = "panel", legend = "bottomright") +
# geom_point(aes(x = main_data$SiteLong, y = main_data$SiteLat), data = main_data, size = 1, color = "orange") +
# ggtitle ("All RLS/MPA sites (not grouped yet)")
## Now map all the sites coloured by their geogroup and check that they look ok on the grid
#these are the grid lines for 0.5degree - THIS ALSO TAKES A LONG TIME
#hlines <- seq(min(main_data$SiteLat),max(main_data$SiteLat),by=0.5) # create a sequence of 0.5 degree
#vlines <- seq(min(main_data$SiteLong),max(main_data$SiteLong),by=0.5)
#ggmap(australia, extent = "panel", legend = "bottomright") +
#geom_point(aes(x = main_data$SiteLong, y = main_data$SiteLat), data = main_data, size = 1, color = main_data$geogroup) +
#scale_y_continuous(limits = c(-44.00, -37.00), expand = c(0, 0)) +
#scale_x_continuous(limits = c(143.00, 150.00), expand = c(0, 0)) +
# geom_vline(xintercept = vlines) +
# geom_hline(yintercept = hlines) +
# ggtitle("Grouping of RLS/MPA sites based on geographic grid") +
#xlab("Longitutde") + ylab("Latitude")
#Get some summary statistics about the geographic groups. For the plot purposes the annual cell temperature is calculated as a mean over all years. In analyses we use annual temperature
rls_aus_geo <- main_data %>%
group_by(geogroup) %>%
summarise (location = first(Location), latt = round(mean(SiteLat),3), long = round(mean(SiteLong),3), year = n_distinct(year), surveys = n_distinct(SurveyID), locatnum = n_distinct(Location), anntemp = mean(meansst), species = n_distinct(TAXONOMIC_NAME), gdd = mean(scaledGDD))
## Now plot the geographic groups but the colour of the dot reflects the mean geosite temperature
rls_aus_geo$tempF <- floor(rls_aus_geo$anntemp) #round the annual SST to the nearest degree
colvector <- list(NA)
colfunc <- colorRampPalette(c("yellow", "red")) #create colour ramp pallele
tempcol = colfunc(18) # sample 18 colours from it, as the difference between min and max geosite temperature is 18 degrees
colvector$col <- tempcol
colvector$tempF <- seq(from = 12, to = 29)
# add a temperature colour identifier to each geosite
rls_aus_geo$color <- colvector$col[match(rls_aus_geo$tempF, colvector$tempF)]
#load long term location coordinates
load(file = "inputs/longLoc.RData")
## Or the location names and coordinates are also given here
#1 BassSt -39.44452 147.2600
#2 Bichen -41.87929 148.3118
#3 Jervis -35.08387 150.7708
#4 Jurien -30.38433 115.0224
#5 Maria -42.58866 148.0122
#6 Ninepi -43.28544 147.1565
#7 Port D -43.32945 145.9253
#8 Port P -38.24981 144.7030
#9 Tinder -43.06525 147.3322
#Plot sites on a shapefile
rgdal::readOGR(dsn = ".", "aust_cd66states") %>%
fortify() %>%
ggplot() +
geom_path(aes(x = long, y = lat, group = group), color = 'darkgrey', size = .3) +
geom_point(aes(x = rls_aus_geo$long, y = rls_aus_geo$latt), data = rls_aus_geo, size = (rls_aus_geo$species/30), color = rls_aus_geo$color) +
geom_point(aes(x = longLoc$long, y = longLoc$lat), data = longLoc, shape = 8, size = 2, color = "black") +
geom_text(x=111.5, y=-30, label= "Jurien Bay", size = 4, fontface = 3) +
geom_text(x=154, y=-35, label= "Jervis Bay", size = 4, fontface = 3) +
geom_text(x=144, y=-37, label= "Port Phillip Bay", size = 4, fontface = 3) +
geom_text(x=151, y=-39, label= "Bass Strait", size = 4, fontface = 3) +
geom_text(x=151, y=-41.5, label= "Bicheno", size = 4, fontface = 3) +
geom_text(x=152, y=-42.8, label= "Maria Island", size = 4, fontface = 3) +
geom_text(x=152.7, y=-44, label= "Ninepin & Tinderbox", size = 4, fontface = 3) +
geom_text(x=142.5, y=-43, label= "Port Davey", size = 4, fontface = 3) +
ggtitle("Mean annual SST of each geographic cell (12 to 29)") +
xlab("Longitutde") + ylab("Latitude")
#ggmap(australia, extent = "panel", legend = "bottomright") +
# geom_point(aes(x = rls_aus_geo$long, y = rls_aus_geo$latt), data = rls_aus_geo, size = (rls_aus_geo$species/30), color = rls_aus_geo$color) +
# ggtitle("Mean annual SST of each geographic cell (12 to 29), circle size proportional to species number") +
# xlab("Longitutde") + ylab("Latitude")
```
### Daily SST values to get temperature statistics
This chunk does not have to be run because the main datafile already has SST statistics associated with each geographic cell. However, it is included here in case someone wants to do different analyses or calcualte different temperature statistics. Thanks to Mike Sumner (Australian Antarctic Division) for help with the SST data!
```{r, warning=FALSE, message=FALSE, eval = F, echo = F}
### DAILY MODEL DATA
## load daily SST values for the 280 geographic cells (each identified with a unique number)
load(file = "inputs/dailySST.RData")
#Calculate mean annual temperature for each geogroup (cell) and save
meangeoSST <- dailyTemp %>% group_by(geogroup, year) %>% summarise (annSST = mean(sst), count = n())
save(meangeoSST, file = "inputs/meangeoSST.RData")
```
### Supplementary Figure 4: are species distributed lognormally? Mostly
```{r, warning=FALSE, message=FALSE, echo = F, eval = T, fig.width=10, fig.height=6}
#rename the data frame
df <- main_data
#set factor levels
df$TAXONOMIC_NAME <- factor(df$TAXONOMIC_NAME)
df$geogroup <- factor(df$geogroup)
#there are actually more size classes in the data set, but for plotting purposes we don't use largest size classes. Missing size classes will be shown as NA. This is not the size inforamtion used in the main analyses
df$Size <- factor(as.character(round(df$SizeClass, 1)),
levels = c("2.5", "5", "7.5", "10", "12.5", "15", "20", "25", "30", "35", "37.5", "40", "50", "62.5", "75", "87.5", "100"))
spp <- unique(df$TAXONOMIC_NAME)
## select which species to plot. For manuscript purposes I plot only 20 species
#For other species change the index of species to plot in the line below
df_summary <- df %>% filter (TAXONOMIC_NAME %in% spp[c(1:20)]) %>% group_by(TAXONOMIC_NAME, Size) %>% summarise(n = n())
ggplot(df_summary, aes(x = Size, y = n, group = TAXONOMIC_NAME)) +
geom_point() + geom_line() +
facet_wrap( ~ TAXONOMIC_NAME, scale = "free_y") +
labs(x = "Size (cm)", y = "Abundance") +
theme_bw() +
theme(
axis.text.x = element_text(angle=90, hjust=1, vjust=.5, size = 6),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)
```
### Supplementary Figure 2: Plot size-temperature distributions in space
Two example plots are provided in the manuscript electronic supplement. Plots for all species are available on https://github.com/astaaudzi/RLSfishSize/tree/master/AllSizePlots
```{r warning=FALSE, message=FALSE, echo=FALSE, eval = F}
load(file = "inputs/fish_data.RData")
#overwrite dataset name so I can use Shane's code
df <- main_data
##rm(fish_temp)
Species <- sort(unique(df$TAXONOMIC_NAME))
for (aa in 1:length(Species)) {
SpeciesName <- Species[aa]
print(SpeciesName)
print(aa)
#prepare data
df$y <- log(df$SizeClass)
df_fit <- df %>% filter(TAXONOMIC_NAME == SpeciesName)
df_fit$X1 <- (df_fit$meansst - mean(df_fit$meansst)) / sd(df_fit$meansst)
df_fit$X2 <- df_fit$X1^2
yVals <- sort(unique(df$SizeClass)) # fish size classes
I <- length(yVals) # number of fish size classes
yCuts <- rep(0, I-1) # fish sizes that split size classes
for (i in 2:I) {
yCuts[i-1] <- log(0.5*(yVals[i-1] + yVals[i]))
}
## plot sizes
df_means <- df_fit %>%
group_by(meansst) %>%
summarise(mu = mean(y), n = n(), ln10 = log10(n)) %>%
arrange(meansst)
sizeplot <- ggplot(df_fit, aes(x = meansst, y = y)) +
geom_point(color = "grey80", size = 0.5) + # observed data
geom_point(data = df_means, aes(x = meansst, y = mu, size = ln10), color = "dark red") +
ylim(0.5, 4.5) +
labs(
title = SpeciesName, subtitle = "grey dots show all observed size classes",
size = "no.ind\n(log10)", x = "Mean cell annual SST (C)", y = "Mean log length (cm)") +
theme_bw()
ggsave (filename = paste("SizePlotsSpatial/",SpeciesName,".jpg",sep=""), plot = sizeplot, width = 8, height = 7)
rm(sizeplot)
}
```
### First set of Bayesian analyses: split the data
Based on initial analyses, some species need higher or lower priors to ensure that their posteriors are within priors. This chunk does not need to be run now, because final estimates of slopes are provided
```{r, warning=FALSE, message=FALSE, echo = F, eval = F}
#List of species
Species <- sort(unique(df$TAXONOMIC_NAME))
## species that should be repeated with increased beta0 priors (2.0 to 5.0) - use code spatial_largerb0.stan
higherB0 <- c("Achoerodus gouldii", "Achoerodus viridis", "Aplodactylus arctidens", "Caranx melampygus", "Caranx sexfasciatus", "Cheilodactylus spectabilis", "Dactylophora nigricans", "Diagramma labiosum", "Heterodontus portusjacksoni", "Hipposcarus longiceps", "Kyphosus bigibbus","Kyphosus cinerascens","Kyphosus sydneyanus", "Kyphosus sectatrix","Latridopsis forsteri","Lethrinus nebulosus","Lutjanus bohar", "Naso tonganus", "Plectropomus leopardus","Seriola lalandi") #20 spp
## decrease beta0 priors (0.5 to 3.0) = use code spatial_lowerb0.stan
lowerB0 <- c("Apogon doederleini", "Brachaluteres jacksonianus", "Chromis atripes", "Chromis margaritifer", "Chromis nitida", "Chromis viridis", "Cirrhilabrus exquisitus", "Cirripectes filamentosus", "Dascyllus aruanus", "Dascyllus reticulatus", "Pomacentrus coelestis","Pomacentrus lepidogenys","Pomacentrus moluccensis", "Valenciennea muralis") #14
#these species need higher priors for size error term (0.2 to 0.6) = use code spatial_higherSigma.stan
higherSigma <- c("Acanthaluteres vittiger", "Acanthochromis polyacanthus", "Amphiprion akindynos", "Cheilinus chlorourus", "Cheilinus trilobatus", "Cheilodipterus quinquelineatus", "Chlorurus sordidus", "Choerodon rubescens", "Chromis hypsilepis", "Cirrhilabrus punctatus", "Coris auricularis", "Coris batuensis", "Coris bulbifrons", "Coris picta", "Dischistodus prosopotaenia", "Gomphosus varius", "Halichoeres margaritaceus", "Halichoeres marginatus", "Halichoeres melanochir", "Halichoeres melanurus", "Halichoeres miniatus", "Halichoeres nebulosus", "Halichoeres nigrescens", "Hemigymnus fasciatus", "Hemigymnus melapterus", "Labrichthys unilineatus", "Labropsis australis","Macropharyngodon meleagris", "Notolabrus gymnogenis", "Notolabrus parilus", "Notolabrus tetricus", "Ophthalmolepis lineolatus", "Ostorhinchus aureus", "Parupeneus spilurus", "Pempheris multiradiata","Pomacentrus adelus","Pomacentrus bankanensis","Pomacentrus grammorhynchus","Pomacentrus vaiuli", "Pomacentrus wardi","Pseudolabrus luculentus", "Scarus frenatus", "Scarus ghobban", "Scarus niger", "Scarus prasiognathos", "Scarus rivulatus", "Scarus schlegeli", "Thalassoma lunare", "Thalassoma lutescens", "Upeneichthys vlamingii") #50
#these species need lower priors for size (0.01 to 0.15) = use code spatial_lowerSigma.stan
lowerSigma <- c("Acanthurus blochii", "Acanthurus grammoptilus", "Acanthurus nigricauda", "Arripis trutta", "Caesio caerulaurea", "Chromis ternatensis", "Hemitaurichthys polylepis","Lutjanus fulviflamma", "Lutjanus gibbus", "Lutjanus quinquelineatus", "Monodactylus argenteus", "Mugil cephalus", "Mulloidichthys flavolineatus", "Mulloidichthys vanicolensis", "Myripristis violacea", "Myripristis vittata", "Naso brevirostris", "Paracaesio xanthura", "Pseudocaranx georgianus", "Pterocaesio digramma", "Pterocaesio tile", "Pterocaesio trilineata", "Sphyraena obtusata", "Trachurus declivis")#24
#these species need 1500 iterations and 1000 burn-in = use spatial_main.stan
longerRuns <- c("Trachurus novaezelandiae", "Schuettea scalaripinnis", "Trachinops taeniatus", "Trachinops caudimaculatus", "Trachinops noarlungae")
#remaining species for which initial priors were suitable = use spatial_main.stan
mainSpecies <- which((!Species %in% higherB0) & (!Species %in% longerRuns) & (!Species %in% lowerB0) & (!Species %in% higherSigma) & (!Species %in% lowerSigma)) #222 species
df_main1 <- df %>% filter(TAXONOMIC_NAME %in% Species[mainSpecies[c(1:70)]])
save(df_main1, file = "data1.RData")
df_main2 <- df %>% filter(TAXONOMIC_NAME %in% Species[mainSpecies[c(71:140)]])
save(df_main2, file = "data2.RData")
df_main3 <- df %>% filter(TAXONOMIC_NAME %in% Species[mainSpecies[c(141:length(Species))]])
save(df_main3, file = "data3.RData")
df_higherB0 <- df %>% filter(TAXONOMIC_NAME %in% higherB0)
save(df_higherB0, file = "data4.RData")
df_lowerB0 <- df %>% filter(TAXONOMIC_NAME %in% lowerB0)
save(df_lowerB0, file = "data5.RData")
df_longer <- df %>% filter(TAXONOMIC_NAME %in% longerRuns)
save(df_longer, file = "data6.RData")
df_higherSigma <- df %>% filter(TAXONOMIC_NAME %in% higherSigma)
save(df_higherSigma, file = "data7.RData")
df_lowerSigma <- df %>% filter(TAXONOMIC_NAME %in% lowerSigma)
save(df_lowerSigma, file = "data8.RData")
```
### First set of Bayesian analyses: main analysis code
The data files above were analysed on clusters and this is the code to be run for the main spatial analysis. Analyses don't have to be run here because ouputs are saved and available. The main analysis is done using the spatial_main.stan code. For some species spatial analyses had to be repeated with updated priors (higher b0 or lower b0) and related .stan files are named accordingly
```{r, warning=FALSE, message=FALSE, echo = F, eval = F}
library(rstan)
library(tidyverse)
#Bayesian analyses are run for each species separately
for (x in 1:length(higherB0)) {
#for (x in 1:length(Species)) {
sppno <- higherB0[x]
SpeciesName <- Species[sppno]
print(SpeciesName)
print(sppno)
#SpeciesName <- Species[x] #select the species
#print(SpeciesName)
#print(x)
### prepare data
df$y <- log(df$SizeClass)
df_fit <- df %>% filter(TAXONOMIC_NAME == SpeciesName)
df_fit$X1 <- (df_fit$meansst - mean(df_fit$meansst)) / sd(df_fit$meansst)
df_fit$X2 <- df_fit$X1^2
yVals <- sort(unique(df$SizeClass)) # fish size classes
I <- length(yVals) # number of fish size classes
yCuts <- rep(0, I-1) # fish sizes that split size classes
for (i in 2:I) {
yCuts[i-1] <- log(0.5*(yVals[i-1] + yVals[i]))
}
###
df_stan <- df %>%
filter(TAXONOMIC_NAME == SpeciesName) %>%
mutate(z1 = meansst - mean(meansst)) %>% # rescale size for fitting
dplyr::select(year, month, day, geogroup, z1, SizeClass) %>%
mutate(
survey_date = as.Date(paste(year, month, day, sep = "-")),
survey = paste(survey_date, geogroup, sep = "-")
) %>%
arrange(survey) %>%
mutate(indx_srv = as.integer(factor(survey)))
# add random factor indexes for year, location, and sample
years <- sort(unique(df_stan$year))
df_years <- tibble(year = years, indx_year = 1:length(years))
grps <- sort(unique(df_stan$geogroup))
df_grps <- tibble(geogroup = grps, indx_grp = 1:length(grps))
df_yVals <- tibble(SizeClass = yVals, indx_sc = 1:length(yVals))
df_stan <- left_join(df_stan, df_years, by = "year")
df_stan <- left_join(df_stan, df_grps, by = "geogroup")
df_stan <- left_join(df_stan, df_yVals, by = "SizeClass")
df_n <- df_stan %>%
group_by(indx_srv, indx_sc) %>%
summarise(n = n())
max_sc <- length(yVals) # max(df_n$indx_sc)
max_srv <- max(df_n$indx_srv)
m_obs <- matrix(data = 0, nrow = max_srv, ncol = max_sc)
for (i in 1:nrow(df_n)) {
m_obs[df_n$indx_srv[i],df_n$indx_sc[i]] <- df_n$n[i]
}
df_srv <- df_stan %>%
group_by(indx_srv) %>%
summarise(
z1 = median(z1),
year = median(indx_year),
grp = median(indx_grp)
)
stan_dat <- list(
N = nrow(df_srv), # surveys
J = max(df_srv$grp), # locations
K = length(yCuts) + 1, # fish size classes
L = max(df_srv$year), # years of data
cutoff = yCuts, # size class cut-offs
y = m_obs, # observations per size class
x = df_srv$z1, # predictor variable
gloc = df_srv$grp, # locations
yr = df_srv$year # year
)
fit <- stan(file = 'stan_models/spatial_main.stan', data = stan_dat, iter = 1000, warmup = 500, chains = 3, seed = 66, refresh = 250)
save(fit, file = paste("... place for saved fit results.../",SpeciesName,".RData",sep="")) #NOTE, saved fit results are not provided, but can be generated with this code
}
```
### STAN code for the spatial analyses
NOTE! This does not run in R, but has to be supplied as .stan file. All files are available in the stan_models subfolder
``` {r, warning=FALSE, message=FALSE, echo = F, eval = F}
// Shane A Richards 6/11/2018
// includes a random effect associated with location, year, and survey
// combines identical observations
data {
int <lower = 1> N; // number of surveys
int <lower = 1> J; // number of locations
int <lower = 1> K; // number of size classes
int <lower = 1> L; // number of year classes
real <lower = 0> cutoff[K-1]; // size class cut-offs
matrix[N,K] y; // observed fish size classes
real x[N]; // observed predictor variable
int <lower = 1, upper = J> gloc[N]; // observed location
int <lower = 1, upper = L> yr[N]; // observed year (index only)
}
parameters {
real <lower = 1.5, upper = 3.5> beta0; // mean (log)size
real <lower = -0.50, upper = 0.5> beta1; // predictor of mean (log)size
// real <lower = 2.0, upper = 5.0> beta0; // mean (log)size for larger b0 analyses
real <lower = 0.10, upper = 0.30> sigma_size; // variation in (log)sizes
real <lower = 0.001, upper = 1.0> sigma_gloc; // variation among locations
real <lower = 0.001, upper = 1.5> sigma_yr; // variation among years
real <lower = 0.001, upper = 1.0> sigma_srv; // variation among years
real gloc_RE[J]; // estimated location-specific variation
real yr_RE[L]; // estimated year-specific variation
real srv_RE[N]; // estimated survey-specific variation
}
transformed parameters {
}
model {
vector[K-1] cpr;
vector[K] pr;
// real cpr[K-1] = 0.0; // cumulative normal probability
// real pr[K] = 0.0; // probability of observed size class
real mu; // mean log fish size
real eps = 0.01; // a small probability
real c1;
real c2;
c1 = (1.0 - eps);
c2 = eps/K;
// generate location and year specific variation
gloc_RE ~ normal(0.0, sigma_gloc);
yr_RE ~ normal(0.0, sigma_yr);
srv_RE ~ normal(0.0, sigma_srv);
for (i in 1:N) { // for each survey
mu = beta0 + beta1*x[i] + gloc_RE[gloc[i]] + yr_RE[yr[i]] + srv_RE[i];
for (k in 1:(K-1)) {
cpr[k] = normal_cdf(cutoff[k], mu, sigma_size);
}
pr[1] = c1*cpr[1] + c2;
for (k in 2:(K-1)) {
pr[k] = c1*(cpr[k] - cpr[k-1]) + c2;
}
pr[K] = c1*(1.0 - cpr[K-1]) + c2;
for (k in 1:K) {
target += y[i,k]*log(pr[k]); // add the log-likelihood term
}
}
}
```
### Spatial postanalyses processing: traceplots
this code was used to assess convergence; individual species traceplots are not provided here, but can be reproduced using the chunks above and this code
```{r, warning=FALSE, message=FALSE, echo = F, eval = F}
myspp <- sort(unique(df$TAXONOMIC_NAME))
##Plot traceplots and posterior distributions
model_params <- c("beta0", "beta1", "sigma_size", "sigma_gloc", "sigma_yr", "sigma_srv")
l_trace <- vector("list", 1) # create an empty list
l_plots <- vector("list", 1) # create an empty list
#plot all diagnostics into one pdf file
pdf(file="diagnostics.pdf",onefile=TRUE)
for (i in 1:length(myspp)) {
SpeciesName <- myspp[i] #select the species
print(SpeciesName)
print(i)
#load saved outputs from individual Bayesian analyses
load(file = paste("...save outputs here... /",SpeciesName,".RData",sep=""))
l_trace[[i]] <- traceplot(fit, pars = model_params, inc_warmup = TRUE, ncol = 3)
print(traceplot(fit, pars = model_params, inc_warmup = TRUE, ncol = 3))
extracted <- rstan::extract(fit, pars=model_params)
df_prm_pdf <- reshape2::melt(extracted, value.name="Parameter")
# plot posterior distributions
df_prm_pdf$L1 <- factor(df_prm_pdf$L1, levels = c("beta0", "beta1",
"sigma_size", "sigma_gloc", "sigma_yr", "sigma_srv"))
l_plots[[i]] <- ggplot(data=df_prm_pdf, aes(x = Parameter)) +
labs(title = SpeciesName) +
geom_density(fill = "wheat") +
labs(
x = "Parameter Value",
y = "Probability density"
) +
facet_wrap( ~ L1, scale = "free", ncol=3) +
theme_bw()
print(ggplot(data=df_prm_pdf, aes(x = Parameter)) +
labs(title = SpeciesName) +
geom_density(fill = "wheat") +
labs(
x = "Parameter Value",
y = "Probability density"
) +
facet_wrap( ~ L1, scale = "free", ncol=3) +
theme_bw())
print(i)
}
dev.off()
```
### Extract posterior distribution quantiles from individual Bayesian analyses
this chunk does not need to be run because outputs are saved and provided separately
```{r, warning=FALSE, message=FALSE, echo = F, eval = F}
load(file = "inputs/fish_data.RData")
df <- main_data
Species <- sort(unique(df$TAXONOMIC_NAME))
##Now get confidence intervals
model_params <- c("beta0", "beta1", "sigma_size", "sigma_gloc", "sigma_yr", "sigma_srv")
l_CI <- vector("list", 1) # create an empty list
for (i in 1:length(Species)) {
SpeciesName <- Species[i]
print(SpeciesName)
print(i)
#enter the directory for saved Bayesian fits from the chunk above
load(file = paste("...save outputs here... /",SpeciesName,".RData",sep=""))
extracted <- rstan::extract(fit, pars=model_params)
df_prm_pdf <- reshape2::melt(extracted, value.name="Parameter")
df_summary <- df_prm_pdf %>% group_by(L1) %>%
summarise(
n= n(), # samples
p.025 = quantile(Parameter, probs = 0.025),
p.100 = quantile(Parameter, probs = 0.100),
p.500 = quantile(Parameter, probs = 0.500),
p.900 = quantile(Parameter, probs = 0.900),
p.975 = quantile(Parameter, probs = 0.975)
)
l_CI[[i]] <- df_summary
}
l_CI335 <- l_CI
### And put results in a dataframe
bet1ci = data.frame(NA, nrow = length(Species), ncol = 19)
for (i in 1:length(Species)) {
SpeciesName <- Species[i]
print(SpeciesName)
print(i)
#beta0 intervals
bet1ci[i,1] <- l_CI[[i]]$p.025[1]
bet1ci[i,2] <- l_CI[[i]]$p.100[1]
bet1ci[i,3] <- l_CI[[i]]$p.500[1]
bet1ci[i,4] <- l_CI[[i]]$p.900[1]
bet1ci[i,5] <- l_CI[[i]]$p.975[1]
#beta1 intervals
bet1ci[i,6] <- l_CI[[i]]$p.025[2]
bet1ci[i,7] <- l_CI[[i]]$p.100[2]
bet1ci[i,8] <- l_CI[[i]]$p.500[2]
bet1ci[i,9] <- l_CI[[i]]$p.900[2]
bet1ci[i,10] <- l_CI[[i]]$p.975[2]
#sigma size intervals
bet1ci[i,11] <- l_CI[[i]]$p.025[4]
bet1ci[i,12] <- l_CI[[i]]$p.100[4]
bet1ci[i,13] <- l_CI[[i]]$p.500[4]
bet1ci[i,14] <- l_CI[[i]]$p.900[4]
bet1ci[i,15] <- l_CI[[i]]$p.975[4]
bet1ci[i,16] <- df %>% filter (TAXONOMIC_NAME == SpeciesName) %>% summarise(mid = first(midpoint))
bet1ci[i,17] <- df %>% filter (TAXONOMIC_NAME == SpeciesName) %>% summarise(Lmax = first(MaxLenFB))
bet1ci[i,18] <- df %>% filter (TAXONOMIC_NAME == SpeciesName) %>% summarise(Lmax = first(MaxSizeObs))
bet1ci[i,19] <- SpeciesName
}
colnames(bet1ci) = c("b0_p025","b0_p10","b0_p50","b0_p90","b0_p975","p025","p10","p50","p90","p975","sigsize_p025","sigsize_p10","sigsize_p50","sigsize_p90","sigsize_p975","midpoint","MaxLenFB","MaxLenObs","species")
save(bet1ci, file = "analysesOutputs/slopesInSpace335spp.RData")
```
### Supplementary Table1: print spatial slopes
```{r, warning=FALSE, message=FALSE, echo = F, eval = T}
load(file = "analysesOutputs/slopesInSpace335spp.RData")
slopes_to_print <- bet1ci %>% select(species, MaxLenObs, midpoint, p025, p10, p50, p90, p975)
colnames(slopes_to_print) = c("species","MaxObservLength","preferred_temp","b1_p025","b1_p10","b1_p50","b1_p90","b1_p975")
knitr::kable(slopes_to_print)
#write.csv(slopes_to_print, file = "ExtendedDataFigures/ExtendedDataTable1.csv")
```
### Fig1A: second spatial Bayesian analysis, effects of temperature midpoint
```{r, warning=FALSE, message=FALSE, echo = F, eval = T, fig.width=10, fig.height=6}
load(file = "analysesOutputs/slopesInSpace335spp.RData")
df <- bet1ci %>% dplyr::select (p025, p10, p50, p90, p975, midpoint, MaxLenObs, species)
#make a data file for regression
df_fit <- df %>%
mutate(
# SD1 = (p90-p10)/(2*1.281552),
SD = (p975-p025)/(2*1.96), #presumably we just need a z score for this
x = midpoint
) %>%
select(Species = species, x, y = p50, SD)
df_fit <- na.omit(df_fit)
x_mean <- mean(df_fit$x) # rescaling value
stan_dat <- list(
N = nrow(df_fit), # Number of species
x = df_fit$x - x_mean, # transformed x-val
SD = df_fit$SD, # SD of y-values
y = df_fit$y # y-values
)
#Run second baysian analysis on the overall slopes of all species
#fit <- stan(file = 'stan_models/spatial_secondFit.stan', data = stan_dat,
# iter = 3500, warmup = 1000, chains = 4, seed = 111, thin = 10)
#save(fit, file = "analysesOutputs/spaceSlope_temp_fit.RData")
load(file = "analysesOutputs/spaceSlope_temp_fit.RData")
#extract params, beta2 is a quadratic parameter and we can see that it is non-zero
model_params <- c("beta0", "beta1", "sigma")
# display the posterior distribution statistics
#print(fit, pars = model_params, probs = c(0.025,0.5,0.975), digits=5)
#traceplot(fit, pars = model_params, inc_warmup = TRUE, ncol = 4)
l_params <- rstan::extract(fit, pars = model_params)
df_prm_pdf <- reshape2::melt(l_params, value.name="Value")
names(df_prm_pdf)[ncol(df_prm_pdf)] <- "Parameter"
# plot posterior distributions
df_prm_pdf$Parameter <- factor(df_prm_pdf$Parameter,
levels = model_params)
#ggplot(data=df_prm_pdf, aes(x = Value, fill = Parameter)) +
# geom_density() +
# labs(
# x = "Value",
# y = "Probability density"
# ) +
# facet_wrap( ~ Parameter, scale = "free") +
# theme_bw()
## Now we create 1000 slopes of temperature responses along 100 values of tempreature ranging from min and max midpoints using 1000 posterior infered values. From these 1000 slopes we get 2.5, 50 and 97.5% quantiles to define the overall uncertainty of response
x_num <- 100
max_iterations <- max(df_prm_pdf$iterations)
m_mu <- matrix(data = 0, nrow = max_iterations, ncol = x_num)
x_vals <- seq(from = min(df_fit$x), to = max(df_fit$x), length.out = x_num)
for (i in 1:max_iterations) {
beta0 <- l_params$beta0[i]
beta1 <- l_params$beta1[i]
m_mu[i, ] <- beta0 + beta1*(x_vals - x_mean)
}
df_CI <- tibble(
x = x_vals,
mu_025 = 0,
mu_500 = 0,
mu_975 = 0
)
# Get quantile values for the uncertainty ranges
for (i in 1:x_num) {
df_CI$mu_025[i] <- quantile(m_mu[ ,i], probs = 0.025)
df_CI$mu_500[i] <- quantile(m_mu[ ,i], probs = 0.500)
df_CI$mu_975[i] <- quantile(m_mu[ ,i], probs = 0.975)
}
#Or use 80%
#for (i in 1:x_num) {
# df_CI$mu_025[i] <- quantile(m_mu[ ,i], probs = 0.1)
# df_CI$mu_500[i] <- quantile(m_mu[ ,i], probs = 0.500)
# df_CI$mu_975[i] <- quantile(m_mu[ ,i], probs = 0.9)
#}
#define the uncertainty polygon to be plotted
df_polygon <- tibble(
x = c(df_CI$x,rev(df_CI$x)),
y = c(df_CI$mu_025,rev(df_CI$mu_975))
)
#assign colour to species depending on their resposes
df_fit <- df_fit %>%
mutate(sig = ifelse(y < 0, ifelse(y + 2*SD < 0, -1, 0), ifelse(y - 2*SD > 0, 1, 0)))
df_fit$sig <- factor(df_fit$sig)
#or use my old way to colour and add error bars
#first add p10 and p90 percentiles from teh Baysian fit
df_fit$p10 <- bet1ci$p10[match(df_fit$Species, bet1ci$species)]
df_fit$p90 <- bet1ci$p90[match(df_fit$Species, bet1ci$species)]
df_fit$color <- 0
df_fit$color[which(df_fit$p90 < 0)] <- -1
df_fit$color[which(df_fit$p10 > 0)] <- 1
df_fit$color <- factor(df_fit$color)
data_subset0 <- df_fit %>% filter(color == -1) #decreasing
data_subset1 <- df_fit %>% filter(color == 1) # increasing
data_subset2 <- df_fit %>% filter(color == 0) #no change
p1 <- ggplot(df_CI) +
geom_abline(intercept = 0, slope = 0, linetype = "dashed") +
# geom_point(data = df_fit, aes(x = x, y = y, color = color)) +
geom_point(data = data_subset2, aes(x = x, y = y, col = "grey")) +
geom_errorbar(data = data_subset2, aes(x = x, ymin = p10, ymax = p90, color = "grey"), width=0) +
geom_point(data = data_subset1, aes(x = x, y = y, color = "blue")) +
geom_errorbar(data = data_subset1, aes(x = x, ymin = p10, ymax = p90, color = "blue"), width=0) +
geom_point(data = data_subset0, aes(x = x, y = y, color = "red")) +
# geom_errorbar(data = df_fit, aes(x = x, ymin = p10, ymax = p90, color = color), width=0) +
geom_errorbar(data = data_subset0, aes(x = x, ymin = p10, ymax = p90, color = "red"), width=0) +
geom_polygon(data = df_polygon, aes(x = x, y = y), fill = "#feb24c") +
geom_line(aes(x = x, y = mu_500)) +
labs(
x = expression("Species thermal affinity ("~degree~"C)"),
y = expression("Relative change in body length (per "~degree~"C)")
) +
ylim(-0.25, 0.25) + # add ylim to remove the outlier
# xlim (-0.03, 0.03) +
scale_colour_manual(values=c("#de2d26", "grey70", "#3182bd")) +
guides(color=FALSE) +
# geom_vline(xintercept = 23, linetype = "dashed") +
theme_bw() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.x = element_text(size=14),
axis.title.y = element_text(size=14),
axis.text=element_text(size=12)
)
p1
```
### Fig1B: second spatial Bayesian analysis, effects of maximum body size
```{r, warning=FALSE, message=FALSE, echo = F, eval = T, fig.width=10, fig.height=6}
#rm(list = ls()) # clear memory
#Load the space first Bayesian CI data (cleaned out, so it has 320 species)
load(file = "analysesOutputs/slopesInSpace335spp.RData")
df <- bet1ci %>% dplyr::select (p025, p10, p50, p90, p975, midpoint, MaxLenFB, MaxLenObs, species)
########
#Or if testing effects of 10% data exclusion
#load(file = "RDataOutputs/testExcl.RData")
#spp = testExcl$species
#df_test <- df[-which(df$species %in% spp),]
#df_test2 <- df[which(df$species %in% spp),]
#replace 20 values with the df matrix with the new results without any data exclusion
#df_test2$p025 <- testExcl$p025[match(df_test2$species, testExcl$species)]
#df_test2$p10 <- testExcl$p10[match(df_test2$species, testExcl$species)]
#df_test2$p50 <- testExcl$p50[match(df_test2$species, testExcl$species)]
#df_test2$p90 <- testExcl$p90[match(df_test2$species, testExcl$species)]
#df_test2$p975 <- testExcl$p975[match(df_test2$species, testExcl$species)]
#df_excl <- rbind(df_test, df_test2)
#save(df_excl, file = "RDataOutputs/df_exclusionTest.RData")
#for the purposes of analyses below replace df with new dataset
#df <- df_excl
########
df_fit <- df %>%
mutate(
SD = (p975-p025)/(2*1.96),
x = log(MaxLenObs)
) %>%
select(Species = species, x, y = p50, SD)
x_mean <- mean(df_fit$x) # rescaling value
stan_dat <- list(
N = nrow(df_fit), # Number of species
x = df_fit$x - x_mean, # transformed x-val
SD = df_fit$SD, # SD of y-values
y = df_fit$y # y-values
)
#Fit second Bayesian model - don't need to run it, as results are saved
#fit <- stan(file = 'stan_models/spatial_secondFit.stan', data = stan_dat,
# iter = 3500, warmup = 1000, chains = 4, seed = 111, thin = 10)
#save(fit, file = "analysesOutputs/spaceSlope_length_fit.RData")
## Load the main fit data set
load(file = "analysesOutputs/spaceSlope_length_fit.RData")
model_params <- c("beta0", "beta1", "sigma")
# display the posterior distribution statistics
#print(fit, pars=model_params, probs=c(0.025,0.5,0.975), digits=5)
##Baysian results with 20 values replaced without data exclusion
# mean se_mean sd 2.5% 50% 97.5% n_eff Rhat
#beta0 -0.00496 0.00007 0.00198 -0.00877 -0.00501 -0.00101 768 0.99744
#beta1 0.01828 0.00012 0.00342 0.01157 0.01828 0.02469 874 1.00176
#sigma 0.02805 0.00006 0.00180 0.02449 0.02807 0.03150 971 0.99840
#Baysian result of the original analysis
# mean se_mean sd 2.5% 50% 97.5% n_eff Rhat
#beta0 -0.00484 0.00007 0.00197 -0.00868 -0.00479 -0.00117 826 1.00231
#beta1 0.01948 0.00011 0.00334 0.01330 0.01937 0.02585 973 0.99698
#sigma 0.02811 0.00007 0.00180 0.02477 0.02811 0.03161 757 1.00706
#traceplot(fit, pars = model_params, inc_warmup = TRUE, ncol = 4)
l_params <- rstan::extract(fit, pars = model_params)
df_prm_pdf <- reshape2::melt(l_params, value.name="Value")
names(df_prm_pdf)[ncol(df_prm_pdf)] <- "Parameter"
# plot posterior distributions
df_prm_pdf$Parameter <- factor(df_prm_pdf$Parameter, levels = model_params)
#ggplot(data=df_prm_pdf, aes(x = Value, fill = Parameter)) +
# geom_density() +
# labs(
# x = "Value",
# y = "Probability density"
# ) +
# facet_wrap( ~ Parameter, scale = "free") +
# theme_bw()
## Now run the same iterations as above to get
x_num <- 100
max_iterations <- max(df_prm_pdf$iterations)
m_mu <- matrix(data = 0, nrow = max_iterations, ncol = x_num)
x_vals <- seq(from = min(df_fit$x), to = max(df_fit$x), length.out = x_num)
for (i in 1:max_iterations) {
beta0 <- l_params$beta0[i]
beta1 <- l_params$beta1[i]
m_mu[i, ] <- beta0 + beta1*(x_vals - x_mean)
}
df_CI <- tibble(
x = x_vals,
mu_025 = 0,
mu_500 = 0,
mu_975 = 0
) %>%
mutate(x_orig = 10^x)
for (i in 1:x_num) {
df_CI$mu_025[i] <- quantile(m_mu[ ,i], probs = 0.1)
df_CI$mu_500[i] <- quantile(m_mu[ ,i], probs = 0.500)
df_CI$mu_975[i] <- quantile(m_mu[ ,i], probs = 0.9)
}
df_polygon <- tibble(
x = c(df_CI$x,rev(df_CI$x)),
y = c(df_CI$mu_025,rev(df_CI$mu_975))
) %>%
mutate(x_orig = 10^x)
df_fit <- df_fit %>% mutate(x_orig = 10^x)
df_fit$p10 <- bet1ci$p10[match(df_fit$Species, bet1ci$species)]
df_fit$p90 <- bet1ci$p90[match(df_fit$Species, bet1ci$species)]
df_fit$color <- 0
df_fit$color[which(df_fit$p90 < 0)] <- -1
df_fit$color[which(df_fit$p10 > 0)] <- 1
df_fit$color <- factor(df_fit$color)
ranlen = runif(n = length(df_fit$x), min = 0.05, max = 0.15)
df_fit$x_rand <- df_fit$x + ranlen
data_subset0 <- df_fit %>% filter(color == -1) #decreasing
data_subset1 <- df_fit %>% filter(color == 1) # increasing
data_subset2 <- df_fit %>% filter(color == 0) #no change
p2 <- ggplot(df_CI) +
geom_abline(intercept = 0, slope = 0, linetype = "dashed") +
# geom_point(data = df_fit, aes(x = x, y = y, color = color)) +
geom_point(data = data_subset2, aes(x = x_rand, y = y, col = "grey")) +
geom_errorbar(data = data_subset2, aes(x = x_rand, ymin = p10, ymax = p90, color = "grey"), width=0) +
geom_point(data = data_subset1, aes(x = x_rand, y = y, color = "blue")) +
geom_errorbar(data = data_subset1, aes(x = x_rand, ymin = p10, ymax = p90, color = "blue"), width=0) +
geom_point(data = data_subset0, aes(x = x_rand, y = y, color = "red")) +
# geom_errorbar(data = df_fit, aes(x = x_rand, ymin = p10, ymax = p90, color = color), width=0) +
geom_errorbar(data = data_subset0, aes(x = x_rand, ymin = p10, ymax = p90, color = "red"), width=0) +
geom_polygon(data = df_polygon, aes(x = x, y = y), fill = "#feb24c") +
geom_line(aes(x = x, y = mu_500)) +
labs(
x = expression("Maximum body length, cm"),
y = expression("Relative change in body length (per "~degree~"C)")
) +
scale_colour_manual(values=c("#de2d26", "grey70", "#3182bd")) +
ylim(-0.25, 0.25) +
scale_x_continuous(breaks=c(log(20), log(50), log(150)), labels=c("20", "50", "150")) +
guides(color=FALSE) +
theme_bw() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.x = element_text(size=14),
axis.title.y = element_text(size=14),
axis.text=element_text(size=12)
)
p2
plot_grid(p1, p2, labels = c("A", "B"), label_size = 26)
```
### Supplementary Table 2: spatial statistics
```{r, warning=F}
load(file = "analysesOutputs/slopesInSpace335spp.RData")
length(which(bet1ci$p50 < 0)) # 189 have negative slopes
length(which(bet1ci$p50 > 0)) # 146 have positive slopes (larger where warmer)
length(which(bet1ci$p90 < 0)) # 97 species have negative significant responses
length(which(bet1ci$p10 > 0)) # 64 have significant positive responses
increasing <- bet1ci[which(bet1ci$p10 > 0),]
decreasing <- bet1ci[which(bet1ci$p90 < 0),]
tempSpace <- bet1ci %>% filter (midpoint <= 23) #temperate species
tropSpace <- bet1ci %>% filter (midpoint > 23) #tropical species
## analysis for temperate and tropical separately
### temperate
length(which(tempSpace$p10 > 0)) #33
length(which(tempSpace$p90 < 0)) #35
# proportion from significantly changing species (68 in total)
length(which(tempSpace$p10 > 0))/68
length(which(tempSpace$p90 < 0)) / 68
#proportion from all temporal
length(which(tempSpace$p50 > 0)) #57
length(which(tempSpace$p50 > 0))/length(tempSpace$species) #0.49
length(which(tempSpace$p50 < 0)) #59
length(which(tempSpace$p50 < 0))/length(tempSpace$species) #0.51
### tropical
length(which(tropSpace$p10 > 0)) #31
length(which(tropSpace$p90 < 0)) #62
# proportion from significantly changing species (93 in total)
length(which(tropSpace$p10 > 0))/(31+62)
length(which(tropSpace$p90 < 0)) / (31+62)
#proportion from all temporal
length(which(tropSpace$p50 > 0)) #88
length(which(tropSpace$p50 > 0))/length(tropSpace$species) #0.40
length(which(tropSpace$p50 < 0)) #130
length(which(tropSpace$p50 < 0))/length(tropSpace$species) #0.60
```
### Supplementary Figure 3: testing if exclusion of juveniles might affect Fi1B results
The full analysis is not given here, as it is a repeat of the analysis above for 20 species, but with all size data included.
First get the data