-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis.Rmd
2619 lines (1876 loc) · 76.5 KB
/
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: "Revised Analysis of phenological shifts in Germany"
output:
html_notebook: default
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(fig.align = "center", echo = FALSE)
# disable dplyr::summarise() grouping message
# also disable stringsasfactors
options(dplyr.summarise.inform = FALSE,
stringsAsFactors = FALSE)
library("data.table")
library("rgbif")
library("raster")
library("broom.mixed")
library("lme4")
library("cowplot")
library("magick")
# tidyverse stuff last to avoid masking these functions
library("magrittr")
library("forcats")
library("stringr")
library("ggplot2")
library("tidyr")
library("dplyr")
library("tidyselect")
## Functions ----------------------------------------------
source("scripts/functions.R")
# Control variables -------------------------------------------------
## Script control -----------------------------------------
# check if notebook is rendered from script and whether script control is
# overridden
if (exists("override_control")) {
use_notebook_control <- override_control
} else {
use_notebook_control <- TRUE
}
if (use_notebook_control) {
# name of analysis
# as a prerequisite, scripts have to be available under scripts/analysis_dname/
analysis_dname <- "full_analysis_data/"
# do an overall test run?
# this will mean working with a dataset with reduce number of species
# so everything will be faster
test_run <- FALSE
## Data getting:
# run script for retrieving climate data from DWD regardless of data being
# already present?
force.clim.get <- FALSE
# run script for retrieving plant trait data from bioFlor regardless of data
# being already present?
force.traits.get <- FALSE
# force running of occurrence getting script
force.occ.get <- FALSE
# control which of the downloaded files to delete
# - "all": delete both .zip files and extracted occ .txt files
# - "zip": delete only .zip files, keep .txt
# - "txt": delete only .txt files, keep .zip
# - "non": keep all files in download folder
delete.occ.download <- "all"
# force pruning of data and addition of climate and elevation
force.occ.prune <- FALSE
## Modeling
# force running of model generation script
force.models <- FALSE
# run model script independently?
# * models will be taken from the testing model formula file
# * no checks will be performed whether the models are appropriate for the main
# analysis
# * The results will not be integrated into the analysis
run.models.ind <- test_run
# how to treat predictor variables
# not currently used
center_preds <- FALSE
scale_preds <- FALSE
# save plot of random regression slopes over data?
# will add additional running time, increasing with # of data points
plot_rnd_slopes <- FALSE
# save diagnostics plots
# will take a very long time on the full dataset
plot_diagnostics <- FALSE
#save faceted plots of diagnostic plots
plot_diagnostics_facet <- FALSE
# set number of times a model with failed convergence will attempt to restart
n_restart <- 2
## Plot saving
# save plots to disk?
save_plots <- TRUE
# save tables (as .docx)?
save_tables <- TRUE
}
## Path names ---------------------------------------------
# get paths for various analysis specific dirs
data_dir <- paste0("data/", analysis_dname)
script_dir <- paste0("scripts/", analysis_dname)
if (!test_run) {
dat_occ_file <- paste0(data_dir, "occurrences_full_pruned_clim_elev.csv")
dat_slope_temp_file <- paste0(data_dir, "rnd_eff_temp.csv")
dat_slope_year_file <- paste0(data_dir, "rnd_eff_year.csv")
} else {
dat_occ_file <- paste0(data_dir, "occurrences_full_pruned_clim_elev_test.csv")
dat_slope_temp_file <- paste0(data_dir, "rnd_eff_temp_test.csv")
dat_slope_year_file <- paste0(data_dir, "rnd_eff_year_test.csv")
}
### Model formula stuff
# set model formula paths
mod_form_base <- "static_data/model_formulas/"
mod_form_dir <- paste0(mod_form_base, analysis_dname)
# check if analysis specific formulas exist
if (!dir.exists(mod_form_dir)) {
mod_form_dir <- paste0(paste0(mod_form_base, "default/"))
}
# set appropriate path
if (!test_run && !run.models.ind) {
mod_form_file <- paste0(mod_form_dir, "model_formulas.txt")
} else {
mod_form_file <- paste0(mod_form_dir, "model_formulas_test.txt")
}
## Set graphics parameters --------------------------------
# set colour for raw data points
col.pt <- "black"
# set alpha for raw data points
alpha.pt <- 0.5
# set alpha for raw data lines
alpha.ln <- 0.2
# set size of data lines
size.dat.line <- 2
# set colour for static lines
col.stc.line <- "gray40"
# set colour for axis elements
col.ax <- "gray40"
# ribbon alpha
alpha.ribbon <- 0.3
# set col for annotations
col.annot <- "gray31"
# size of annotations
size.annot.txt <- 3
# colors for density gradients
col.grad.low <- "gray"
col.grad.high <- "black"
## define custom plotting theme ---------------------------
theme_shifts <- function (...) {
theme_minimal() %+replace%
theme(panel.grid = element_blank(), ...)
}
## define clearer group names -----------------------------
# set named vector for recoding group names to common names
recode.vec <- c(
"Plants" = "Plants",
"Coleoptera" = "Beetles",
"Diptera" = "Flies",
"Hymenoptera" = "Bees",
"Lepidoptera" = "Butterflies/\nMoths"
)
# make alternative vector for interactions
recode.vec.int <- c("Hoverfly" = "Hoverfly - Plant",
"Bee" = "Bee - Plant",
"Butterfly" = "Butterfly - Plant")
# recode vec for PollDep
recode.vec.PollDep <- c("Yes" = "Pollinator dependent",
"Intermediate" = "Intermediate",
"No" = "Pollinator independent"
)
### set colour tables -------------------------------------------------------
# define colours
# DO NOT CHANGE ORDER, only append
col.grp <-
data.frame(group = c("Beetles",
"Flies",
"Bees",
"Butterflies/\nMoths",
"Insects overall",
"Plants",
"Hoverfly - Plant",
"Bee - Plant",
"Butterfly - Plant",
"Overall",
"Pollinator dependent",
"Intermediate",
"Pollinator independent"),
colour = c("#9815db",
"#f41d0f",
"#ffa500",
"#4744ff",
"gold",
"#008a00",
"#f41d0f",
"#ffa500",
"#4744ff",
"deepskyblue",
"red",
"#ffa500",
"#008a00")
)
# alternative: named vector
col.grp.vec <- col.grp$colour
names(col.grp.vec) <- col.grp$group
#set colors for Plant-Pollinator comparisons
col.plapoll <- col.grp[5:6,]
# static polls group (no exclusion)
col.poll.stc <- col.grp[1:4,]
#only for polls
col.poll <- col.grp[1:4,]
#only for plants
col.plant <- col.grp[6,]
#set colors for group comparisons (add plant group at the end)
col.group.stc <- bind_rows(col.poll.stc, col.plant)
col.group <- bind_rows(col.poll, col.plant)
#set colors for group comparisons including overall
col.group2.stc <- bind_rows(col.poll.stc, col.plapoll)
col.group2 <- bind_rows(col.poll, col.plapoll)
#set colors for PollDep comparisons
col.PollDep <- col.grp[11:13,]
# interaction colors with standard names
col.int.stc <- col.grp[7:9,]
col.int.stc$group <- c("Hoverfly", "Bee", "Butterfly")
#set colors for Interaction comparisons
col.int <- col.grp[7:9,]
#set colors for Interaction comparison with overall group
col.int2 <- col.grp[7:10,]
#set colors for Interaction group comparisons
col.int3 <- bind_rows(col.int, col.plant)
# colours for id.grps with scientific scheme
# TODO: Apply colour scheme throughout notebook
col.group.sci <- col.grp$colour[c(1:4, 6)]
names(col.group.sci) <- c("Coleoptera",
"Diptera",
"Hymenoptera",
"Lepidoptera",
"Plants")
```
```{r Ensure additional data is present}
# Plant trait data ----------------------------------------
if (file.exists('static_data/bioflor_traits.csv')) {
run.traits.get <- FALSE
} else {
run.traits.get <- TRUE
}
if (run.traits.get | force.traits.get) {
source('scripts/get_bioflor_traits.R')
}
if (!file.exists(paste0("static_data/plant_pollinator_interactions_for_",
"potential_networks_2018.csv"))) {
stop(paste0("Interaction data not found, please download and place the",
"file in the static_data directory.\nDownload from ",
"'https://doi.org/10.5285/6d8d5cb5-bd54-4da7-903a-15bd4bbd531b'."))
}
```
```{r get_occurrence_data, include=FALSE}
# for now, only check whether data and random effects are present
if (!all(file.exists(dat_occ_file)) ||
force.occ.get ||
force.occ.prune) {
if (!test_run) {
source("scripts/get_occ_data_all_in_one.R")
} else {
# this script automatically ensures full data is present
source("scripts/get_occ_test_data.R")
}
}
if (!all(file.exists(dat_slope_temp_file, dat_slope_year_file)) ||
force.models ||
run.models.ind) {
source("scripts/run_models.R")
}
```
```{r load_occurrence_slope_data}
# load plant trait data
plant_traits <- fread("static_data/bioflor_traits.csv",
na.strings = c("", "NA")) %>%
# recode PollDep to use clearer names
mutate(PollDep = recode_factor(PollDep, !!! recode.vec.PollDep))
# load occurrence data
dat.occ <- fread(dat_occ_file, showProgress = FALSE) %>%
# add trait data
left_join(plant_traits, by = "species") %>%
# recode id.grp to use trivial names
# (recode only takes name/value pairs, so !!! expansion necessary)
mutate(id.grp = recode_factor(id.grp, !!! recode.vec)) %>%
# order factor levels so that PollDep is in order
# of increasing slope
mutate(PollDep = fct_relevel(PollDep, recode.vec.PollDep))
# load slope data
slopes_temp <- fread(dat_slope_temp_file)
slopes_year <- fread(dat_slope_year_file)
# re-scale data
if (scale_preds) {
sd_temp <- sd(dat.occ$temp)
slopes_temp <- slopes_temp %>%
mutate(slope = slope / sd_temp,
slope_std_err = slope_std_err / sd_temp)
sd_year <- sd(dat.occ$year)
slopes_year <- slopes_year %>%
mutate(slope = slope / sd_year,
slope_std_err = slope_std_err / sd_year)
}
if (center_preds) {
scale_mean_temp <- mean(dat.occ$temp / sd(dat.occ$temp))
slopes_temp <- slopes_temp %>%
mutate(intercept = intercept - slope * scale_mean_temp)
scale_mean_year <- mean(dat.occ$year / sd(dat.occ$temp))
slopes_year <- slopes_year %>%
mutate(intercept = intercept - slope * scale_mean_year)
}
# add taxonomic and trait data to slopes
col_vec <- c("kingdom",
"phylum",
"id.grp",
"order",
"family",
"genus",
"species")
tax_df <- dat.occ %>%
select(all_of(col_vec)) %>%
distinct()
# load data on species sample sizes
species_n <- fread(paste0(data_dir, "n_species_pruned_sum.csv")) %>%
# recode id.grp to use trivial names
# (recode only takes name/value pairs, so !!! expansion necessary)
mutate(id.grp = recode_factor(id.grp, !!! recode.vec))
slopes_temp <- slopes_temp %>%
# add taxonomic data
left_join(tax_df, by = "species") %>%
# add trait data
left_join(plant_traits, by = "species") %>%
# add species sample sizes
left_join(species_n, by = c("id.grp", "species"))
slopes_year <- slopes_year %>%
# add taxonomic data
left_join(tax_df, by = "species") %>%
# scale slopes and std_err from days per year to days per decade
mutate(slope = slope * 10,
slope_std_err = slope_std_err * 10) %>%
# add trait data
left_join(plant_traits, by = "species") %>%
# add species sample sizes
left_join(species_n, by = c("id.grp", "species"))
# generate df giving slopes for both vars
slopes_all <- left_join(slopes_temp,
slopes_year,
by = c("kingdom",
"phylum",
"id.grp",
"order",
"family",
"genus",
"n",
names(plant_traits)),
suffix = c("_temp", "_year")) %>%
# drop redundant cols
select(-starts_with(c("group_",
"main_var_")))
```
```{r show_record_sizes_by_group}
dat_nrec <- fread(paste0(data_dir, "n_records_by_idgrp_pruned.csv"),
showProgress = FALSE) %>%
# recode id.grp to use trivial names
# (recode only takes name/value pairs, so !!! expansion necessary)
mutate(id.grp = recode_factor(id.grp, !!! recode.vec)) %>%
rename(Group = id.grp, `n records` = n_rec, `n species` = n_species,
`Min records per species` = min_species_rec,
`Max records per species` = max_species_rec,
`Median records per species` = median_species_rec)
dat_nrec
```
```{r plot_record_distributions}
record_dist_plot <- ggplot(dat.occ,
aes(year, col = id.grp)) +
geom_bar(size = 5, position = "dodge", width = 0.8, orientation = "x") +
labs(x = "Year",
y = "# Records") +
facet_wrap( ~ id.grp,
nrow = 2,
scales = "free_y") +
scale_y_log10() +
scale_color_manual(name = "Group",
aesthetics = c("color", "fill"),
values = col.grp.vec) +
theme_shifts(legend.position = "none")
record_dist_plot
```
```{r analyze_time_temp_association}
dat.temp <- dat.occ %>%
select(year, temp, lat, long) %>%
# reconstruct climate tiles from lat and long
mutate(lat = cut(lat,
breaks = seq(min(floor(lat)),
max(ceiling(lat)),
0.5)),
long = cut(long,
breaks = seq(min(floor(long)),
max(ceiling(long)),
0.5))) %>%
distinct() %>%
mutate(lat = str_extract_all(lat, "[0-9\\.]+"),
long = str_extract_all(long, "[0-9\\.]+")) %>%
mutate(lat = sapply(lat, function(x) mean(as.numeric(x))),
long = sapply(long, function(x) mean(as.numeric(x)))) %>%
group_by(year) %>%
# summarize(temp = mean(temp)) %>%
ungroup()
lm_time_temp <- lm(data = dat.temp, temp ~ year)
lm_time_temp_sum <- summary(lm_time_temp)
r_sqare <- lm_time_temp_sum[["adj.r.squared"]]
slope <- coef(lm_time_temp_sum)[2,1]
slope_sig <- coef(lm_time_temp_sum)[2,4] %>% cut(
breaks = c(0, 0.001, 0.01, 0.05, 0.1, 1),
labels = c("***", "**", "*", ".", " "),
right = FALSE )
time_temp_plt <- ggplot(dat.temp, aes(year, temp)) +
geom_point() +
stat_summary(geom = "line", fun.data = mean_se, fun.args = 1.96) +
geom_smooth(method = "lm", formula = y ~ x) +
stat_summary(col = "red", fun.data = mean_se, fun.args = 1.96) +
geom_text(aes(x = mean(unique(year)), y = ypos(temp, frac = 0.1),
label = paste(
paste("R² =", round(r_sqare, 2)),
paste("slope =", round(slope * 10, 2), "[\u00B0C / decade]"),
slope_sig,
sep = "\n")),
col = col.annot) +
labs(x = "Year",
y = "Temperature [\u00B0C] (\u00B1 95% CI)") +
ylim(NA, ypos(dat.temp$temp, frac = 0.2)) +
theme_shifts(legend.position = "none")
time_temp_plt +
labs(title = "Change in temperature at record location")
```
```{r plot_shifts}
if (test_run) {
for (id.grp.var in unique(dat.occ$id.grp)) {
dat.occ.plt <- dat.occ %>% filter(id.grp == id.grp.var)
slopes.plt <- slopes_year %>% filter(id.grp == id.grp.var)
print(
ggplot() +
geom_point(data = dat.occ.plt,
aes(year, doy, col = id.grp)) +
geom_abline(data = slopes.plt,
aes(intercept = intercept, slope = slope),
col = col.stc.line) +
facet_wrap(~ species) +
scale_color_manual(name = "Group",
values = col.grp.vec) +
theme_shifts()
)
}
}
```
## Analysis of differences between groups in shift
```{r boxplot_between_group_diffs}
ggplot(slopes_temp,
aes(id.grp, slope, fill = id.grp)) +
geom_hline(yintercept = 0) +
geom_boxplot() +
labs(x = "Group",
y = "Slope [days / \u00B0C]") +
scale_fill_manual(values = col.grp.vec) +
theme_shifts(legend.position = "none")
ggplot(slopes_year,
aes(id.grp, slope, fill = id.grp)) +
geom_hline(yintercept = 0) +
geom_boxplot() +
labs(x = "Group",
y = "Slope [days / decade]") +
scale_fill_manual(values = col.grp.vec) +
theme_shifts(legend.position = "none")
```
```{r analyse_between_group_diffs}
cat("Differences in slope with temperature:\n\n")
aov_temp <- aov(data = slopes_temp, slope ~ id.grp,
# weights = 1 / (slope_std_err ^ 2)
)
summary(aov_temp)
cat("\n Significant pairwise differences: \n")
ph_aov_temp <- TukeyHSD(aov_temp)
ph_aov_temp$id.grp[ph_aov_temp$id.grp[, 4] < 0.05,]
cat("\n\n")
cat("----------------------------------------------------------\n\n")
cat("Differences in slope over time:\n\n")
aov_year <- aov(data = slopes_year, slope ~ id.grp,
# weights = 1 / (slope_std_err ^ 2)
)
summary(aov_year)
cat("\n Significant pairwise differences: \n")
ph_aov_year <- TukeyHSD(aov_year)
ph_aov_year$id.grp[ph_aov_year$id.grp[, 4] < 0.05,]
```
## Summary of Shifts
```{r summarize_slopes}
slopes_temp_sum <- slopes_temp %>%
group_by (id.grp) %>%
summarise(n_spec = length(slope),
slope_mean = mean(slope),
slope_sd = sd(slope),
# slope_sem = sqrt(sum(slope_std_err ^ 2)) / length(slope),
slope_sem = slope_sd / sqrt(n_spec),
slope_ci_min = slope_mean - slope_sem * 1.96,
slope_ci_max = slope_mean + slope_sem * 1.96,
p_diff_zero = t.test(slope)$p.value,
slope_n_corr = cor(slope, log10(n)),
slope_n_corr_p = cor.test(slope, log10(n),
method = "pearson")$p.value,
slope_frac_negative = sum(slope < 0) / length(slope),
var = "Temperature") %>%
# adjust diff zero & slope_n_corr pval for multiple testing
mutate(p_diff_zero_adj = p.adjust(p_diff_zero, method = "fdr"),
slope_n_corr_p_adj = p.adjust(slope_n_corr_p, method = "fdr")) %>%
# add significance letters
mutate(pairw_grp = sig_letters(ph_aov_temp$id.grp, order = recode.vec))
slopes_year_sum <- slopes_year %>%
group_by (id.grp) %>%
summarise(n_spec = length(slope),
slope_mean = mean(slope),
slope_sd = sd(slope),
# slope_sem = sqrt(sum(slope_std_err ^ 2)) / length(slope),
slope_sem = slope_sd / sqrt(n_spec),
slope_ci_min = slope_mean - slope_sem * 1.96,
slope_ci_max = slope_mean + slope_sem * 1.96,
p_diff_zero = t.test(slope)$p.value,
slope_n_corr = cor(slope, log10(n),
method = "pearson"),
slope_n_corr_p = cor.test(slope, log10(n))$p.value,
slope_frac_negative = sum(slope < 0) / length(slope),
var = "Year") %>%
# adjust diff zero & slope_n_corr pval for multiple testing
mutate(p_diff_zero_adj = p.adjust(p_diff_zero, method = "fdr"),
slope_n_corr_p_adj = p.adjust(slope_n_corr_p, method = "fdr")) %>%
# add significance letters
mutate(pairw_grp = sig_letters(ph_aov_year$id.grp, order = recode.vec))
#combine both summary data sets and display them
slopes_all_sum <- left_join(slopes_temp_sum,
slopes_year_sum,
by = c("id.grp"),
suffix = c("_temp",
"_year")) %>%
# drop redundant columns
select(-starts_with("var_"))
slopes_all_sum
```
```{r correlate_species_n_with_slope}
# do corr tests on log 10 transformed data
slope_n_temp_corr <- cor.test(log10(slopes_all$n), slopes_all$slope_temp,
method = "pearson")
slope_n_year_corr <- cor.test(log10(slopes_all$n), slopes_all$slope_year,
method = "pearson")
# generate summary strings for plotting
n_temp_corr_str <- paste("r =", round(slope_n_temp_corr$estimate, 2),
", ",
"p =", round(slope_n_temp_corr$p.value, 2))
n_year_corr_str <- paste("r =", round(slope_n_year_corr$estimate, 2),
", ",
"p =", round(slope_n_year_corr$p.value, 2))
slope_n_corr_temp_plt <- ggplot(slopes_all,
aes(n, slope_temp, col = id.grp)) +
geom_point(alpha = alpha.pt) +
# geom_smooth(method = "lm",
# col = "black") +
geom_text(data = slopes_all_sum,
aes(x = 10 ^ mean(c(log10(max(slopes_all$n)),
log10(min(slopes_all$n)))),
y = ypos(slopes_all$slope_temp),
label = paste0("r = ", round(slope_n_corr_temp, 2),
",\n",
"p = ", round(slope_n_corr_p_adj_temp, 2))),
col = col.annot,
hjust = 0.5,
vjust = 0.5,
size = 2.5) +
geom_hline(yintercept = 0) +
facet_wrap(~ id.grp, nrow = 1) +
scale_x_log10() +
scale_color_manual(name = "Group",
aesthetics = c("color", "fill"),
values = col.grp.vec) +
labs(x = "Species n",
y = "Shift with temperature [days / \u00B0C]",
title = "Shift vs sample size",
subtitle = paste0("Overall:", n_temp_corr_str)) +
theme_shifts(axis.text.x = element_text(angle = 45,
hjust = 0.5),
legend.position = "none")
slope_n_corr_temp_plt
slope_n_corr_year_plt <- ggplot(slopes_all,
aes(n, slope_year, col = id.grp)) +
geom_point(alpha = alpha.pt) +
# geom_smooth(method = "lm",
# col = "black") +
geom_text(data = slopes_all_sum,
aes(x = 10 ^ mean(c(log10(max(slopes_all$n)),
log10(min(slopes_all$n)))),
y = ypos(slopes_all$slope_year),
label = paste0("r = ", round(slope_n_corr_year, 2),
",\n",
"p = ", round(slope_n_corr_p_adj_year, 2))),
col = col.annot,
hjust = 0.5,
vjust = 0.5,
size = 2.5) +
geom_hline(yintercept = 0) +
facet_wrap(~ id.grp, nrow = 1) +
scale_x_log10() +
scale_color_manual(name = "Group",
aesthetics = c("color", "fill"),
values = col.grp.vec) +
labs(x = "Species n",
y = "Shift over time [days / decade]",
title = "Shift vs sample size",
subtitle = paste0("Overall:", n_year_corr_str)) +
theme_shifts(axis.text.x = element_text(angle = 45,
hjust = 0.5),
legend.position = "none")
slope_n_corr_year_plt
```
```{r plot_slopes_vs_species_forest}
# save plot for display and plotting
slopes_spec_temp_for_plt <- slopes_temp %>%
# plot slopes in ascending order
ggplot() +
geom_pointrange(aes(x = reorder(species, -slope),
y = slope,
ymin = slope - slope_std_err * 1.96,
ymax = slope + slope_std_err * 1.96,
col = id.grp),
alpha = alpha.pt) +
geom_point(aes(x = reorder(species, -slope),
y = slope,
col = id.grp)) +
# clearly denote the 0 line
geom_hline(yintercept = 0) +
# invert x and y axis for classic forest plot look
coord_flip() +
# break plot into facets, each with an independent species axis
facet_wrap( ~ id.grp, scale = "free_y") +
# add lables
labs(y = "Shift with temperature [days / \u00B0C] (\u00B1 95% CI) ",
x = "Species") +
# add coloring
scale_color_manual(name = "Group",
values = col.grp.vec) +
# remove labeling of individual species (too much information at once)
# remove the legend
theme_shifts(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
legend.position = "none")
# display plot with title
slopes_spec_temp_for_plt +
labs(title = "Shifts with temperature")
# save plot
slopes_spec_year_for_plt <- slopes_year %>%
# plot slopes in ascending order
ggplot() +
geom_pointrange(aes(x = reorder(species, -slope),
y = slope,
ymin = slope - slope_std_err * 1.96,
ymax = slope + slope_std_err * 1.96,
col = id.grp),
alpha = alpha.pt) +
geom_point(aes(x = reorder(species, -slope),
y = slope,
col = id.grp)) +
# clearly denote the 0 line
geom_hline(yintercept = 0) +
# invert x and y axis for classic forest plot look
coord_flip() +
# break plot into facets, each with an independent species axis
facet_wrap( ~ id.grp, scale = "free_y") +
# add lables
labs(y = "Shift over time [days / decade] (\u00B1 95% CI)",
x = "Species") +
# add coloring
scale_color_manual(name = "Group",
values = col.grp.vec) +
# remove labeling of individual species (too much information at once)
# remove the legend
theme_shifts(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
legend.position = "none")
# display plot
slopes_spec_year_for_plt +
labs(title = "Shifts over time")
```
```{r plot_slopes_vs_groups}
# for temp
slopes_grp_temp_mean_plt <- ggplot() +
# # raw data
# geom_point (data = slopes_temp,
# aes(x = id.grp,
# y = slope),
# col = col.pt,
# alpha = alpha.pt,
# position = position_jitter()) +
# error bars
geom_errorbar (data = slopes_temp_sum,
aes(x = id.grp,
ymin = slope_ci_min,
ymax = slope_ci_max,
col = id.grp)) +
# mean data
geom_point (data = slopes_temp_sum,
aes(x = id.grp,
y = slope_mean,
col = id.grp)) +
# pairwise differences
geom_text (data = slopes_temp_sum,
aes(x = id.grp,
y = ypos(slope_ci_max, frac = 0.5),
label = pairw_grp),
col = col.annot) +
# line denoting 0
geom_hline (yintercept = 0,
col = col.stc.line) +