-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnalysis.Rmd
2509 lines (2148 loc) · 124 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: "Analysis: Microhabitats are associated with diversity-productivity relationships in freshwater bacterial communities"
author: "Marian L. Schmidt, [email protected], @micro_marian"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
code_folding: show
highlight: default
keep_md: yes
theme: journal
toc: yes
toc_float:
collapsed: no
smooth_scroll: yes
toc_depth: 3
editor_options:
chunk_output_type: console
---
<style>
pre code, pre, code {
white-space: pre !important;
overflow-x: scroll !important;
word-break: keep-all !important;
word-wrap: initial !important;
}
</style>
#### Purpose of this file
This file has all of the code for the the main analysis to reproduce all figures except Figure S9 in the Schmidt et al. manuscript entitled **"Microhabitats shape diversity-productivity relationships in freshwater bacterial communities"**, published by [FEMS Microbiology Ecology](https://doi.org/10.1093/femsec/fiaa029).
*Note*: To see how to reproduce figure S9 please see the github for this project and go to [analysis/OTU_Removal_Analysis.html](https://deneflab.github.io/Diversity_Productivity/analysis/OTU_Removal_Analysis.html) on the github page.
##### If you have any questions, please be welcome to email the corresponding author at [email protected] or tweet her at [micro_marian](https://twitter.com/micro_marian?lang=en).
```{r setup, include=FALSE}
# For width of code chunks and scroll bar
options(width=250)
knitr::opts_chunk$set(eval = TRUE,
echo = TRUE,
include = TRUE,
warning = FALSE,
collapse = FALSE,
message = FALSE,
dpi=600, #dev = "tiff",
engine = "R", # Chunks will always have R code, unless noted
error = TRUE,
fig.path="figures/", # Set the figure options
fig.align = "center")
```
# Load Libraries
```{r load-libraries}
library(devtools) # Reproducibility (see end of file)
library(phyloseq) # Easier data manipulation
library(picante) # Phylogenetic Tree Analysis
library(tidyverse) # Pretty plotting and data manipulation
library(forcats) # Recoding factors
library(cowplot) # Multiple plotting
library(picante) # Will also include ape and vegan
library(car) # Residual analysis
library(sandwich) # vcovHC function in post-hoc test
library(MASS) # studres in plot_residuals function
library(caret) # Cross validation
library(pander) # Pretty tables
library(glmnet) # Lasso regressions
library(broom) # Stats from lm regression
library(purrr) # Exporting lm results
library(DT) # Fancy HTML table output
library(lme4) # linear mixed effects model
library(iNEXT) # Calculate hill diversity with interpolation & extrapolation
library(hillR) # Calculate phylogenetic hill numbers
library(hilldiv) # Calculate hill phylogenetic hill numbers (for comparison)
library(phytools) # for force.ultrametric()
source("code/Muskegon_functions.R") # Source custom functions
source("code/set_colors.R") # Set Colors for plotting
# Set the ggplot theme
theme_set(theme_cowplot())
```
# Load data
```{r load-data}
# Loads a phyloseq object named otu_merged_musk_pruned)
load("data/surface_PAFL_otu_pruned_raw.RData")
# The name of the phyloseq object is:
surface_PAFL_otu_pruned_raw
# Remove doubletons
surface_PAFL_otu_pruned_rm2 <- prune_taxa(taxa_sums(surface_PAFL_otu_pruned_raw) > 2, surface_PAFL_otu_pruned_raw)
surface_PAFL_otu_pruned_rm2
# How many OTUs left for analysis?
paste("There are", ntaxa(surface_PAFL_otu_pruned_rm2), "OTUs remaining for analysis in the dataset.")
# Remove tree for computational efficiency
surface_PAFL_otu_pruned_notree_rm2 <- phyloseq(tax_table(surface_PAFL_otu_pruned_rm2), otu_table(surface_PAFL_otu_pruned_rm2), sample_data(surface_PAFL_otu_pruned_rm2))
# Gather the metadata in a dataframe
metadata <- data.frame(sample_data(surface_PAFL_otu_pruned_notree_rm2)) %>%
mutate(fraction = factor(fraction, levels = c("WholePart","WholeFree")),
lakesite = factor(lakesite, levels = c("MOT", "MDP", "MBR", "MIN")),
fraction = fct_recode(fraction, Particle = "WholePart", Free = "WholeFree"),
lakesite = fct_recode(lakesite, Outlet = "MOT", Deep = "MDP", Bear = "MBR", River = "MIN"))
row.names(metadata) <- metadata$norep_filter_name
# Replace the sample data
sample_data(surface_PAFL_otu_pruned_notree_rm2) <- metadata
# Create a dataframe for environmental data only
environmental_data <- metadata %>%
dplyr::select(Temp_C:DO_percent, -BGA_cellspermL, -SRP_ugperL, fraction, norep_filter_name, -DO_percent) %>%
dplyr::filter(fraction == "Free") %>%
dplyr::select(-fraction) %>%
tibble::column_to_rownames(var = "norep_filter_name") %>%
dplyr::rename(Temp = Temp_C, SPC = SpCond_uSpercm,
TDS = TDS_mgperL, ORP = ORP_mV,
Chla = Chl_Lab_ugperL, Cl = Cl_mgperL,
SO4 = SO4_mgperL, NO3 = NO3_mgperL,
NH3 = NH3_mgperL, TKN = TKN_mgperL,
TP = TP_ugperL, Alk = Alk_mgperL,
DO = DO_mgperL) %>%
as.matrix()
```
```{r pca-environ}
#### PCA DATA
# Scale the data so their variances are the same!
scaled_enviro <- scale(environmental_data)
# Sanity Checks: check that we get mean of 0 and sd of 1
apply(scaled_enviro, 2, mean)
apply(scaled_enviro, 2, sd)
# Run a redundnacy analysis (RDA) to extract the variation in the set of response variables
pca_environ <- rda(scaled_enviro)
# What is the proportion explained by each of the PCA axes?
summary(pca_environ)$cont$importance
# Pull out all of the PCA scores into a dataframe
pca_scores_df <- summary(pca_environ)$sites %>%
as.data.frame() %>%
tibble::rownames_to_column(var = "norep_filter_name") %>%
mutate(norep_water_name = paste(substr(norep_filter_name, 1, 4), substr(norep_filter_name, 6, 8), sep = "")) %>%
dplyr::select(-c(norep_filter_name, PC3, PC4, PC5, PC6))
# Combine the above dataframe with the rest of the metadata
metadata_pca <- metadata %>%
mutate(norep_water_name = paste(substr(norep_filter_name, 1, 4), substr(norep_filter_name, 6, 8), sep = "")) %>%
left_join(pca_scores_df, by = "norep_water_name")
```
# Calculate Diversity
## Hill Diversity
**Hill diversity with the iNEXT package**
```{r iNEXT-data}
# Prepare the input data for iNEXT
iNEXT_input_table <- otu_table(surface_PAFL_otu_pruned_rm2) %>%
t() %>%
data.frame()
#set.seed(777)
# Run iNEXT on the data - it takes a long time to run! So here we will load in the object that was previously created with the following line of code:
#iNEXT_data <- iNEXT(iNEXT_input_table, q = c(0,1,2), datatype = "abundance")
#save(list="iNEXT_data", file=paste0("data/iNEXT/iNEXT_data_surface_PAFL_otu_pruned_rm2"))
# Load the data
load("data/iNEXT/iNEXT_data_surface_PAFL_otu_pruned_rm2")
#str(iNEXT_data)
# Pull out into a dataframe
div_iNEXT <- iNEXT_data$AsyEst %>%
rename(norep_filter_name = Site)
```
## Phylo Hill Diversity
**Phylogenetic Hill diversity with the hillR package**
```{r calc-hillR}
# Here I will use hillR to calculate the phylogenetic diversity,
# which uses an extension of the hill numbers
#otu_mat <- data.frame(otu_table(surface_PAFL_otu_pruned_rm2))
#phy_tree <- phy_tree(surface_PAFL_otu_pruned_rm2)
set.seed(111)
# Calculate the Hill phylogenetic diversity metric from the hillR package
# The output from this command is a named vector with the sample name and the div value.
#hill_phy0_df <- hill_phylo(comm = otu_mat, tree = phy_tree, q = 0)
#hill_phy1_df <- hill_phylo(comm = otu_mat, tree = phy_tree, q = 1)
#hill_phy2_df <- hill_phylo(comm = otu_mat, tree = phy_tree, q = 2)
# Pull out the sample names
#norep_filter_name <- names(hill_phy0_df)
#stopifnot(names(hill_phy0_df) == names(hill_phy1_df))
#stopifnot(names(hill_phy1_df) == names(hill_phy2_df))
# Pull out the hill phylo div values
#div_sample_names <- rep(norep_filter_name, times = 3)
#phylo_div_vals <- c(unname(hill_phy0_df), unname(hill_phy1_df), unname(hill_phy2_df)) # rich, shannon, simpson
#phylo_div_types <- c(rep("Species richness", times = 24), rep("Shannon diversity", times = 24), rep("Simpson diversity", times = 24))
# Put it all in a dataframe
#hillR_output <- data.frame(div_sample_names, phylo_div_vals, phylo_div_types) %>%
# rename(norep_filter_name = div_sample_names, Diversity = phylo_div_types,
# hillR_phylo = phylo_div_vals)
# save to file because hillR is computationally intensive
#write.csv(x = hillR_output, file = "data/iNEXT/hillR_output.csv", row.names = FALSE, quote = FALSE)
# Because hillR takes so much time to calculate - I'll load in a previously computed version (from the code above)
hillR_output <- read.csv("data/iNEXT/hillR_output.csv") %>%
mutate(Diversity = fct_recode(Diversity, "phylo_richness" = "Species richness",
"phylo_shannon" = "Shannon diversity",
"phylo_simpson" = "Simpson diversity")) %>%
spread(key = Diversity, value = hillR_phylo)
```
**Put together the diversity dataframes into one**
```{r combine-diversity-dfs-prep}
# COMBINE iNEXT AND hillR DATA - should now be 144 rows
div_df <-
div_iNEXT %>%
dplyr::select(norep_filter_name, Diversity, Observed) %>%
mutate(Diversity = fct_recode(Diversity, "richness" = "Species richness",
"shannon" = "Shannon diversity",
"simpson" = "Simpson diversity")) %>%
# For this analysis, we will be using the observed values calculated from iNEXT
spread(key = Diversity, value = Observed) %>%
left_join(hillR_output)
```
## Mean Pairwise Distance
```{r calc-sesmpd, fig.width = 4, fig.height = 4}
# Read in the tree
#RAREFIED_rm2_fasttree <- read.tree(file = "data/PhyloTree/newick_tree_rm2_rmN.tre")
# Load in data that has doubletons removed
#load("data/PhyloTree/surface_PAFL_otu_pruned_RAREFIED_rm2.RData")
#surface_PAFL_otu_pruned_RAREFIED_rm2
# Create the OTU table for picante
#surface_PAFL_RAREFIED_rm2_otu <- matrix(otu_table(surface_PAFL_otu_pruned_RAREFIED_rm2), nrow = nrow(otu_table(surface_PAFL_otu_pruned_RAREFIED_rm2)))
#rownames(surface_PAFL_RAREFIED_rm2_otu) <- sample_names(surface_PAFL_otu_pruned_RAREFIED_rm2)
#colnames(surface_PAFL_RAREFIED_rm2_otu) <- taxa_names(surface_PAFL_otu_pruned_RAREFIED_rm2)
## Calculate input for SES_MPD
# Convert the abundance data to standardized abundanced vegan function `decostand' , NOTE: method = "total"
#otu_decostand_total <- decostand(surface_PAFL_RAREFIED_rm2_otu, method = "total")
# check total abundance in each sample
#apply(otu_decostand_total, 1, sum)
# check for mismatches/missing species between community data and phylo tree
#RAREFIED_rm2_matches <- match.phylo.comm(RAREFIED_rm2_fasttree, otu_decostand_total)
# the resulting object is a list with $phy and $comm elements. replace our
# original data with the sorted/matched data
#phy_RAREFIED_rm2 <- RAREFIED_rm2_matches$phy
#comm_RAREFIED_rm2 <- RAREFIED_rm2_matches$comm
# Calculate the phylogenetic distances
#phy_dist_RAREFIED_rm2 <- cophenetic(phy_RAREFIED_rm2)
## Calculate SES_MPD
###################################### INDEPENDENT SWAP ############################################
# calculate standardized effect size mean pairwise distance (ses.mpd)
#unweighted_sesMPD_indepswap_RAREFIED_rm2 <- ses.mpd(comm_RAREFIED_rm2, phy_dist_RAREFIED_rm2, null.model = "independentswap",
# abundance.weighted = FALSE, runs = 999)
#unweight_sesmpd <- unweighted_sesMPD_indepswap_RAREFIED_rm2 %>% rownames_to_column(var = "norep_filter_name")
#WEIGHTED_sesMPD_indepswap_RAREFIED_rm2 <- ses.mpd(comm_RAREFIED_rm2, phy_dist_RAREFIED_rm2, null.model = "independentswap",
# abundance.weighted = TRUE, runs = 999)
#weight_sesmpd <- WEIGHTED_sesMPD_indepswap_RAREFIED_rm2 %>% rownames_to_column(var = "norep_filter_name")
# Combine them together into a dataframe
#sesmpd_df <- unweight_sesmpd %>%
# dplyr::select(norep_filter_name, mpd.obs.z) %>%
# rename(unweighted_sesmpd = mpd.obs.z) %>%
# left_join(dplyr::select(weight_sesmpd, norep_filter_name, mpd.obs.z), by = "norep_filter_name") %>%
# rename(weighted_sesmpd = mpd.obs.z)
# Gather ALL div data!
#div_df <- div_df %>%
# left_join(sesmpd_df, by = "norep_filter_name")
#write.csv(div_df, file = "data/iNEXT/diversity_measures.csv", quote = FALSE, row.names = FALSE)
```
#### Final dataframe
```{r combine-diversity-dfs-final}
div_df <- read.csv(file = "data/iNEXT/diversity_measures.csv")
# Create the final dataframe!
comb_div_df <- div_df %>%
left_join(metadata_pca, by = "norep_filter_name") %>%
gather(key = "Diversity", value = "Observed", richness:phylo_richness) %>%
data.frame()
head(comb_div_df)
dim(comb_div_df)
# #Prepare dataframe for calculations
div_df_frac <- metadata %>%
dplyr::select(norep_filter_name, fraction, season) %>%
right_join(div_iNEXT, by = "norep_filter_name")
## The following data will the be primary dataframe used in this analysis
# Wide format dataframe for plotting
wide_div_meta_df <- div_df %>%
left_join(metadata_pca, by = "norep_filter_name")
### BASIC STATS OF PRODUCTION AND # OF CELL
std <- function(x) sd(x)/sqrt(length(x))
# For the beginning of the results section
wide_div_meta_df %>%
group_by(fraction) %>%
summarize(avg_cells_per_mL = mean(fraction_bac_abund),
se_cells_per_mL = std(fraction_bac_abund),
avg_community_prod = mean(frac_bacprod),
se_community_prod = std(frac_bacprod))
wide_div_meta_df %>%
dplyr::filter(norep_filter_name != "MOTEJ515") %>%
group_by(fraction) %>%
summarize(avg_log10_percap_prod = mean(log10(fracprod_per_cell)),
se_log10_percap_prod = std(log10(fracprod_per_cell)))
```
# Main Figures
**Have a legend for all plots**
Since there's a set parameter in `set_colors.R` file that was sourced at the beginning, we can use this throughout to can assure that the below legends will represent the legends called afterwards.
```{r legends}
####### Legend for season
legend_plot <- ggplot(metadata, aes(y = frac_bacprod, x = fraction, fill = fraction, shape = season)) +
geom_jitter(size = 3, width = 0.2) +
scale_fill_manual(values = fraction_colors, guide = guide_legend(override.aes = list(shape = 22, size = 4))) +
scale_shape_manual(values = season_shapes, guide = guide_legend(override.aes = list(size = 4))) +
theme(legend.position = "bottom", axis.title.x = element_blank(),
legend.title = element_blank(), legend.justification="center",
plot.margin = unit(c(0.2,0.2,1,0.2), "cm")) # top, right, bottom, and left margins
# Extract the legend
season_legend <- cowplot::get_legend(legend_plot + theme(legend.direction = "horizontal",legend.justification="center" ,legend.box.just = "bottom"))
### Make it 2 rows for plots that are skinnier
####### Legend for season
season_2row_plot <- ggplot(metadata, aes(y = frac_bacprod, x = fraction, fill = fraction, shape = season)) +
geom_jitter(size = 3, width = 0.2) +
scale_fill_manual(values = fraction_colors, guide = guide_legend(override.aes = list(shape = 22, size = 4))) +
scale_shape_manual(values = season_shapes, guide = guide_legend(override.aes = list(size = 4))) +
theme(legend.position = "bottom", legend.justification="center",
axis.title.x = element_blank(),
legend.title = element_blank(), legend.box = "vertical",
legend.spacing.y = unit(0.1, 'cm'),
plot.margin = unit(c(0.2,0.2,1,0.2), "cm")) # top, right, bottom, and left margins
# Extract the legend
season_2row_legend <- cowplot::get_legend(season_2row_plot + theme(legend.direction = "horizontal",legend.justification="center" ,legend.box.just = "bottom"))
####### Legend for lakesite
lakesite_legend <- ggplot(metadata, aes(y = frac_bacprod, x = fraction, fill = fraction, shape = lakesite)) +
geom_jitter(size = 3, width = 0.2) +
scale_fill_manual(values = fraction_colors, guide = guide_legend(override.aes = list(shape = 22, size = 4))) +
scale_shape_manual(values = lakesite_shapes, guide = guide_legend(override.aes = list(size = 4))) +
theme(legend.position = "bottom", axis.title.x = element_blank(),
legend.title = element_blank(), legend.justification="center",
plot.margin = unit(c(0.2,0.2,1,0.2), "cm")) # top, right, bottom, and left margins
# Extract the legend
lakesite_legend <- cowplot::get_legend(lakesite_legend + theme(legend.direction = "horizontal",legend.justification="center" ,legend.box.just = "bottom"))
```
## Figure 1
```{r Figure-1, fig.width = 8.5, fig.height = 3.5}
######################################################### Fraction ABUNDANCe
frac_abund_wilcox <- wilcox.test(log10(as.numeric(fraction_bac_abund)) ~ fraction, data = metadata)
frac_abund_wilcox
metadata %>%
group_by(fraction) %>%
summarize(mean(as.numeric(fraction_bac_abund)))
# Make a data frame to draw significance line in boxplot (visually calculated)
dat1 <- data.frame(a = c(1.1,1.1,1.9,1.9), b = c(6.45,6.5,6.5,6.45)) # WholePart vs WholeFree
poster_a <-
ggplot(filter(metadata, norep_filter_name != "MOTEJ515"),
aes(y = log10(as.numeric(fraction_bac_abund)), x = fraction)) +
geom_jitter(size = 3, aes(fill = fraction, shape = season), width = 0.2) +
geom_boxplot(alpha = 0.5, outlier.shape = NA, aes( fill = fraction)) +
#ylab("Log10(Bacterial Counts) \n (cells/mL)") +
ylab(expression(atop(log[10]*"(Bacterial Counts)", "(cells/mL)"))) +
scale_fill_manual(values = fraction_colors) +
scale_shape_manual(values = season_shapes) +
##### Particle vs free cell abundances
geom_path(data = dat1, aes(x = a, y = b), linetype = 1, color = "gray40") +
annotate("text", x=1.5, y=6.55, size = 8, color = "gray40", label= paste("***")) +
annotate("text", x=1.5, y=6.4, size = 3.5, color = "gray40",
label= paste("p =", round(frac_abund_wilcox$p.value, digits = 6))) +
theme(legend.position = "bottom",
legend.title = element_blank(),
axis.title.x = element_blank())
######################################################### TOTAL PRODUCTION
totprod_wilcox <- wilcox.test(frac_bacprod ~ fraction, data = metadata)
totprod_wilcox
metadata %>%
group_by(fraction) %>%
summarize(mean(frac_bacprod))
# Make a data frame to draw significance line in boxplot (visually calculated)
dat2 <- data.frame(a = c(1.1,1.1,1.9,1.9), b = c(71,72,72,71)) # WholePart vs WholeFree
poster_b <- ggplot(metadata, aes(y = frac_bacprod, x = fraction)) +
geom_jitter(size = 3, aes(fill = fraction, shape = season), width = 0.2) +
geom_boxplot(alpha = 0.5, outlier.shape = NA, aes( fill = fraction)) +
scale_fill_manual(values = fraction_colors, guide = FALSE) +
scale_shape_manual(values = season_shapes) +
scale_y_continuous(limits = c(0, 78), expand = c(0,0), breaks = seq(0, 75, by = 15)) +
#ylab("Community Production \n (μgC/L/day)") +
ylab(expression(atop("Community Production", "(μgC/L/day)"))) +
##### Particle vs free bulk production
geom_path(data = dat2, aes(x = a, y = b), linetype = 1, color = "gray40") +
annotate("text", x=1.5, y=73, size = 8, color = "gray40", label= paste("*")) +
annotate("text", x=1.5, y=69, size = 3.5, color = "gray40",
label= paste("p =", round(totprod_wilcox$p.value, digits = 3))) +
theme(legend.position = "none",
axis.title.x = element_blank())
######################################################### TOTAL PRODUCTION
percellprod_wilcox <- wilcox.test(log10(fracprod_per_cell) ~ fraction, data = filter(metadata, norep_filter_name != "MOTEJ515"))
percellprod_wilcox
filter(metadata, norep_filter_name != "MOTEJ515") %>%
group_by(fraction) %>%
summarize(mean(fracprod_per_cell))
# Make a data frame to draw significance line in boxplot (visually calculated)
dat3 <- data.frame(a = c(1.1,1.1,1.9,1.9), b = c(-5.05,-5,-5,-5.05)) # WholePart vs WholeFree
line_2c <- expression("log" ~~ sqrt(x, y) ~~ "or this" ~~ sum(x[i], i==1, n) ~~ "math expression")
poster_c <- ggplot(filter(metadata, norep_filter_name != "MOTEJ515"),
aes(y = log10(fracprod_per_cell), x = fraction)) +
geom_jitter(size = 3, aes(fill = fraction, shape = season), width = 0.2) +
geom_boxplot(alpha = 0.5, outlier.shape = NA, aes( fill = fraction)) +
scale_fill_manual(values = fraction_colors, guide = FALSE) +
scale_shape_manual(values = season_shapes) +
ylim(c(-8.5, -4.9)) +
ylab(expression(atop(log[10]*"(Per-Capita Production)", "(μgC/cell/day)"))) +
#ylab("Log10(Per-Capita Production) \n(μgC/cell/day)") +
##### Particle vs free per-cell production
geom_path(data = dat3, aes(x = a, y = b), linetype = 1, color = "gray40") +
annotate("text", x=1.5, y=-4.95, size = 8, color = "gray40", label= paste("***")) +
annotate("text", x=1.5, y=-5.15, size = 3.5, color = "gray40",
label= paste("p =", round(percellprod_wilcox$p.value, digits = 5))) +
theme(legend.position = "none",
axis.title.x = element_blank())
######## FIGURE 1
row1_plots <- plot_grid(poster_a + theme(legend.position = "none"), poster_b, poster_c,
labels = c("A", "B", "C"),
ncol = 3, nrow = 1)
fig_1 <- plot_grid(row1_plots, season_legend,
ncol = 1, nrow = 2,
rel_heights = c(1, 0.08)); fig_1
# What are the averages?
metadata %>%
group_by(fraction) %>%
dplyr::select(frac_bacprod, fracprod_per_cell_noinf) %>%
na.omit() %>%
summarize(avg_comm_prod = mean(frac_bacprod),
avg_percell_prod = mean(fracprod_per_cell_noinf),
log10_avg_percell_prod = log10(avg_percell_prod))
```
## Figure 2
```{r Figure-2, fig.width=9, fig.height=3.2}
site_div_order <- c("richness","shannon","simpson","unweighted_sesmpd",
"phylo_richness", "phylo_shannon","phylo_simpson", "weighted_sesmpd")
site_div_labs <- c("{}^0*italic(D)", "{}^1*italic(D)","{}^2*italic(D)", "italic(Unweighted_MPD)",
"{}^0*italic(PD)", "{}^1*italic(PD)","{}^2*italic(PD)", "italic(Weighted_MPD)")
long_div_meta_df <-
wide_div_meta_df %>%
dplyr::select(c(norep_filter_name, richness:weighted_sesmpd, fraction, lakesite, season)) %>%
gather(key = Diversity, value = div_val, richness:weighted_sesmpd) %>%
mutate(Diversity = fct_relevel(Diversity, levels = site_div_order),
hill_labels = factor(Diversity, labels = site_div_labs))
wc_pafl_pvals1 <- c(wilcox.test(richness ~ fraction, data = wide_div_meta_df)$p.value,
wilcox.test(shannon ~ fraction, data = wide_div_meta_df)$p.value,
wilcox.test(simpson ~ fraction, data = wide_div_meta_df)$p.value,
wilcox.test(unweighted_sesmpd ~ fraction, data = wide_div_meta_df)$p.value,
# Row 2
wilcox.test(phylo_richness ~ fraction, data = wide_div_meta_df)$p.value,
wilcox.test(phylo_shannon ~ fraction, data = wide_div_meta_df)$p.value,
wilcox.test(phylo_simpson ~ fraction, data = wide_div_meta_df)$p.value,
wilcox.test(weighted_sesmpd ~ fraction, data = wide_div_meta_df)$p.value)
pafl_pvals_adjusted <- p.adjust(wc_pafl_pvals1, method = "fdr")
wc_pafl_pvals <- c(paste("p=", round(pafl_pvals_adjusted[1], digits = 3), sep = ""),
paste("p=", round(pafl_pvals_adjusted[2], digits = 3), sep = ""),
paste("N", "S", sep = ""),
paste("p=", round(pafl_pvals_adjusted[4], digits = 2), sep = ""),
# Row 2
paste("p=", round(pafl_pvals_adjusted[5], digits = 3),sep = ""),
paste("p=", round(pafl_pvals_adjusted[6], digits = 3), sep = ""),
paste("p=", round(pafl_pvals_adjusted[7], digits = 3), sep = ""),
paste("N", "S", sep = ""))
fraction <- as.character(rep("Free", 8))
# Maximum Diversity Values by Fraction
wide_div_meta_df %>%
group_by(fraction) %>%
summarize(max_rich = max(richness), max_shan = max(shannon), max_simps = max(simpson), max_umpd = max(unweighted_sesmpd),
# row 2
max_phyrich = max(phylo_richness), max_physhan = max(phylo_shannon), max_physimps = max(phylo_simpson), max_wmpd = max(weighted_sesmpd))
# Minimum Diversity Values by Fraction
wide_div_meta_df %>%
group_by(fraction) %>%
summarize(min_rich = min(richness), min_shan = min(shannon), min_simps = min(simpson), max_umpd = min(unweighted_sesmpd),
# row 2
max_phyrich = min(phylo_richness), max_physhan = min(phylo_shannon), max_physimps = min(phylo_simpson), max_wmpd = min(weighted_sesmpd))
# Locations of labels
maxes <- c(1350, 299, 78, 1.35, 150, 15.2, 5.8, 0.1)
df_temp <- data.frame(hill_labels = site_div_labs, wc_pafl_pvals, fraction, maxes)
fig2 <- long_div_meta_df %>%
dplyr::filter(Diversity %in% c("richness", "shannon", "simpson", "unweighted_sesmpd")) %>%
ggplot(aes(y = div_val, x = fraction, fill = fraction)) +
ylab("Value") +
facet_wrap(hill_labels~., scales = "free", labeller = label_parsed, nrow = 2, ncol = 4) +
geom_point(size = 3, position = position_jitterdodge(), aes(shape = season)) +
geom_boxplot(alpha = 0.5, outlier.shape = NA, color = "black") +
scale_fill_manual(values = fraction_colors) +
scale_shape_manual(values = season_shapes) +
scale_color_manual(values = fraction_colors) +
theme(legend.position = "none", axis.title.x = element_blank()) +
geom_text(data = dplyr::filter(df_temp, hill_labels %in% c("{}^0*italic(D)", "{}^1*italic(D)","{}^2*italic(D)", "italic(Unweighted_MPD)")),
aes(x = fraction, y = maxes, label = wc_pafl_pvals), size = 4.5, hjust = 0.5,color = "grey40")
plot_grid(fig2, season_legend, nrow =2, ncol =1, rel_heights = c(1, 0.08))
```
### Linear Models
**Prepare data frames for table S1 and S2**
```{r prep-Table-S1-S2}
## Prepare the dataframes for Free and Particle data
metadata_pca_PD_free <- dplyr::filter(wide_div_meta_df, fraction == "Free")
metadata_pca_PD_part <- dplyr::filter(wide_div_meta_df, fraction == "Particle")
# List of environmental variables to run linear models on
# BGA_cellspermL and Turb_NTU do not have enough data points for regression
lm_variables <- c("frac_bacprod", "fracprod_per_cell_noinf", "Temp_C", "SpCond_uSpercm", "TDS_mgperL",
"pH", "ORP_mV", "Chl_Lab_ugperL", "Cl_mgperL", "SO4_mgperL", "NO3_mgperL",
"NH3_mgperL", "TKN_mgperL", "SRP_ugperL", "TP_ugperL", "Alk_mgperL", "DO_mgperL",
"total_bac_abund","attached_bac", "dnaconcrep1",
"PC1", "PC2",
"richness", "shannon", "simpson", "phylo_richness", "phylo_shannon", "phylo_simpson",
"unweighted_sesmpd", "weighted_sesmpd")
########################################################
############## Particle: Community-wide
lm_summary_particle_comm <- metadata_pca_PD_part %>%
dplyr::select(one_of(lm_variables), -fracprod_per_cell_noinf) %>%
gather(key = independent, value = measurement, -frac_bacprod) %>%
mutate(measurement = as.numeric(measurement)) %>%
group_by(independent) %>%
do(glance(lm(frac_bacprod ~ measurement, data = .))) %>%
mutate(fraction = "Particle", dependent = "Community Production") %>%
dplyr::select(fraction, dependent, independent, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
############## Particle: Per-capita
lm_summary_particle_percap <- metadata_pca_PD_part %>%
dplyr::select(one_of(lm_variables), -frac_bacprod) %>%
filter(!is.na(fracprod_per_cell_noinf)) %>% # Remove samples that are not NA
gather(key = independent, value = measurement, -fracprod_per_cell_noinf) %>%
mutate(measurement = as.numeric(measurement)) %>%
group_by(independent) %>%
do(glance(lm(log10(fracprod_per_cell_noinf) ~ measurement, data = .))) %>%
mutate(fraction = "Particle", dependent = "Per-Capita Production") %>%
dplyr::select(fraction, dependent, independent, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
########################################################
############## Free: Community-wide
lm_summary_free_comm <- metadata_pca_PD_free %>%
dplyr::select(one_of(lm_variables), -fracprod_per_cell_noinf) %>%
gather(key = independent, value = measurement, -frac_bacprod) %>%
mutate(measurement = as.numeric(measurement)) %>%
group_by(independent) %>%
do(glance(lm(frac_bacprod ~ measurement, data = .))) %>%
mutate(fraction = "Free", dependent = "Community Production") %>%
dplyr::select(fraction, dependent, independent, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
############## Free: Per-capita
lm_summary_free_percap <- metadata_pca_PD_free %>%
dplyr::select(one_of(lm_variables), -frac_bacprod) %>%
filter(!is.na(fracprod_per_cell_noinf)) %>% # Remove samples that are not NA
gather(key = independent, value = measurement, -fracprod_per_cell_noinf) %>%
mutate(measurement = as.numeric(measurement)) %>%
group_by(independent) %>%
do(glance(lm(log10(fracprod_per_cell_noinf) ~ measurement, data = .))) %>%
mutate(fraction = "Free", dependent = "Per-Capita Production") %>%
dplyr::select(fraction, dependent, independent, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
## Filtered PCA Linear Model Results
# Put all of the PCA and environmental linear model results together into one dataframe
all_pca_div_environ_lm_results <-
bind_rows(lm_summary_particle_comm, lm_summary_particle_percap,
lm_summary_free_comm, lm_summary_free_percap) %>%
dplyr::rename(independent_var = independent,
dependent_var = dependent)
## Combine the results with the diversity linear models
individual_lm_results <- all_pca_div_environ_lm_results %>%
mutate(AIC = round(AIC, digits = 2),
adj.r.squared = round(adj.r.squared, digits = 2),
p.value = round(p.value, digits = 4),
FDR.p = round(FDR.p, digits = 4)) %>%
rename(FDR.p.value = FDR.p)
```
```{r linear-models}
# Free-Living samples only
div_measures_free <- comb_div_df %>%
dplyr::select(fraction, Observed, Diversity, frac_bacprod, fracprod_per_cell_noinf) %>%
filter(fraction == "Free") %>%
dplyr::select(-fraction)
# Particle-associated samples only
div_measures_part <- comb_div_df %>%
dplyr::select(fraction, Observed, Diversity, frac_bacprod, fracprod_per_cell_noinf) %>%
filter(fraction == "Particle") %>%
dplyr::select(-fraction)
## All of the samples!
div_measures_all <- comb_div_df %>%
dplyr::select(Observed, Diversity, frac_bacprod, fracprod_per_cell_noinf)
########################################################
############## Particle: Community-wide
lm_divs_particle_comm <- div_measures_part %>%
dplyr::select(-fracprod_per_cell_noinf) %>%
group_by(Diversity) %>%
do(glance(lm(frac_bacprod ~ Observed, data = .))) %>%
mutate(fraction = "Particle", dependent = "Community Production") %>%
dplyr::select(fraction, dependent, Diversity, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
############## Particle: Community-wide
lm_divs_particle_percap <- div_measures_part %>%
dplyr::select(-frac_bacprod) %>%
group_by(Diversity) %>%
do(glance(lm(log10(fracprod_per_cell_noinf) ~ Observed, data = .))) %>%
mutate(fraction = "Particle", dependent = "Per-Capita Production") %>%
dplyr::select(fraction, dependent, Diversity, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
########################################################
############## Free: Community-wide
lm_divs_free_comm <- div_measures_free %>%
dplyr::select(-fracprod_per_cell_noinf) %>%
group_by(Diversity) %>%
do(glance(lm(frac_bacprod ~ Observed, data = .))) %>%
mutate(fraction = "Free", dependent = "Community Production") %>%
dplyr::select(fraction, dependent, Diversity, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
############## Free: Community-wide
lm_divs_free_percap <- div_measures_free %>%
dplyr::select(-frac_bacprod) %>%
group_by(Diversity) %>%
do(glance(lm(log10(fracprod_per_cell_noinf) ~ Observed, data = .))) %>%
mutate(fraction = "Free", dependent = "Per-Capita Production") %>%
dplyr::select(fraction, dependent, Diversity, logLik, AIC, adj.r.squared, p.value) %>%
ungroup() %>%
mutate(FDR.p = p.adjust(p.value, method = "fdr"))
# Community-Wide Production
table_comm_wide <- bind_rows(lm_divs_particle_comm, lm_divs_free_comm) %>%
dplyr::select(-dependent) %>%
mutate(AIC = round(AIC, digits = 1),
adj.r.squared = round(adj.r.squared, digits = 3),
p.value = round(p.value, digits = 3),
FDR.p = round(FDR.p, digits = 3))
datatable(table_comm_wide,
caption = "Ordinary least squares regression statistics for community-wide heterotrophic production",
options = list(pageLength = 12), rownames = FALSE)
# Log10 Per-capita Production
table_percap <- bind_rows(lm_divs_particle_percap, lm_divs_free_percap) %>%
dplyr::select(-dependent) %>%
mutate(AIC = round(AIC, digits = 1),
adj.r.squared = round(adj.r.squared, digits = 3),
p.value = round(p.value, digits = 3),
FDR.p = round(FDR.p, digits = 3))
datatable(table_percap,
caption = "Ordinary least squares regression statistics for log10(per-capita production)",
options = list(pageLength = 12), rownames = FALSE)
# Here I will calculate the lms so later we can simply use these objects for plotting.
######################################################### COMMUNITY WIDE PRODUCTION VS DIVERSITY
######################################################### COMMUNITY WIDE PRODUCTION VS DIVERSITY
# linear model for community production vs species richness
lm_prod_vs_rich_PA <- lm(frac_bacprod ~ richness, data = filter(wide_div_meta_df, fraction == "Particle"))
lm_prod_vs_rich_FL <- lm(frac_bacprod ~ richness, data = filter(wide_div_meta_df, fraction == "Free"))
# linear model for community production vs exp(H')
lm_prod_vs_shannon_PA <- lm(frac_bacprod ~ shannon, data = filter(wide_div_meta_df, fraction == "Particle"))
lm_prod_vs_shannon_FL <- lm(frac_bacprod ~ shannon, data = filter(wide_div_meta_df, fraction == "Free"))
# linear model for community production vs inverse simpson
lm_prod_vs_invsimps_PA <- lm(frac_bacprod ~ simpson, data = filter(wide_div_meta_df, fraction == "Particle"))
lm_prod_vs_invsimps_FL <- lm(frac_bacprod ~ simpson, data = filter(wide_div_meta_df, fraction == "Free"))
######################## PHYLOGENETIC HILL DIVERSITY METRICS ################################
# 0D: linear model for community production vs phylogenetic richness
lm_prod_vs_phylorich_PA <- lm(frac_bacprod ~ phylo_richness, data = filter(wide_div_meta_df, fraction == "Particle"))
lm_prod_vs_phylorich_FL <- lm(frac_bacprod ~ phylo_richness, data = filter(wide_div_meta_df, fraction == "Free"))
# 1D: linear model for community production vs phylogenetic exp(H')
lm_prod_vs_phyloshan_PA <- lm(frac_bacprod ~ phylo_shannon, data = filter(wide_div_meta_df, fraction == "Particle"))
lm_prod_vs_phyloshan_FL <- lm(frac_bacprod ~ phylo_shannon, data = filter(wide_div_meta_df, fraction == "Free"))
# 2D: linear model for community production vs phylogenetic inverse simpson
lm_prod_vs_phylosimps_PA <- lm(frac_bacprod ~ phylo_simpson, data = filter(wide_div_meta_df, fraction == "Particle"))
lm_prod_vs_phylosimps_FL <- lm(frac_bacprod ~ phylo_simpson, data = filter(wide_div_meta_df, fraction == "Free"))
######################################################### PER CAPITA PRODUCTION VS DIVERSITY
######################################################### PER CAPITA PRODUCTION VS DIVERSITY
################
# linear model for community production vs species richness
lm_percell_prod_vs_rich_PA <- lm(log10(fracprod_per_cell_noinf) ~ richness,
data = filter(wide_div_meta_df, fraction == "Particle"));
lm_percell_prod_vs_rich_FL <- lm(log10(fracprod_per_cell_noinf) ~ richness,
data = filter(wide_div_meta_df, fraction == "Free"));
# linear model for community production vs exp(H')
lm_percell_prod_vs_shannon_PA <- lm(log10(fracprod_per_cell_noinf) ~ shannon,
data = filter(wide_div_meta_df, fraction == "Particle"))
lm_percell_prod_vs_shannon_FL <- lm(log10(fracprod_per_cell_noinf) ~ shannon,
data = filter(wide_div_meta_df, fraction == "Free"))
# linear model for community production vs inverse simpson
lm_percell_prod_vs_invsimps_PA <- lm(log10(fracprod_per_cell_noinf) ~ simpson,
data = filter(wide_div_meta_df, fraction == "Particle"))
lm_percell_prod_vs_invsimps_FL <- lm(log10(fracprod_per_cell_noinf) ~ simpson,
data = filter(wide_div_meta_df, fraction == "Free"))
######################## PHYLOGENETIC HILL DIVERSITY METRICS ################################
# linear model for community production vs phylogenetic richness
lm_percell_prod_vs_phylorich_PA <- lm(log10(fracprod_per_cell_noinf) ~ phylo_richness,
data = filter(wide_div_meta_df, fraction == "Particle"));
lm_percell_prod_vs_phylorich_FL <- lm(log10(fracprod_per_cell_noinf) ~ phylo_richness,
data = filter(wide_div_meta_df, fraction == "Free"));
# linear model for community production vs phylogenetic exp(H')
lm_percell_prod_vs_phyloshan_PA <- lm(log10(fracprod_per_cell_noinf) ~ phylo_shannon,
data = filter(wide_div_meta_df, fraction == "Particle"))
lm_percell_prod_vs_phyloshan_FL <- lm(log10(fracprod_per_cell_noinf) ~ phylo_shannon,
data = filter(wide_div_meta_df, fraction == "Free"))
# linear model for community production vs inverse simpson
lm_percell_prod_vs_phylosimps_PA <- lm(log10(fracprod_per_cell_noinf) ~ phylo_simpson,
data = filter(wide_div_meta_df, fraction == "Particle"))
lm_percell_prod_vs_phylosimps_FL <- lm(log10(fracprod_per_cell_noinf) ~ phylo_simpson,
data = filter(wide_div_meta_df, fraction == "Free"))
```
## Figure 3
**Prepare Figure 3**
```{r prep-Figure-3}
# FDR Correction
fig3_pvals <- c(summary(lm_prod_vs_rich_PA)$coefficients[,4][2], summary(lm_percell_prod_vs_rich_PA)$coefficients[,4][2],
summary(lm_prod_vs_invsimps_PA)$coefficients[,4][2],summary(lm_percell_prod_vs_invsimps_PA)$coefficients[,4][2]);
fig3_adjusted_pvals <- p.adjust(fig3_pvals, method = "fdr")
######################################################### OBSERVED RICHNESS #########################################################
rich_fraction_wilcox <- wilcox.test(richness ~ fraction, data = wide_div_meta_df)
rich_fraction_wilcox
wide_div_meta_df %>%
group_by(fraction) %>%
summarize(mean(richness), sd(richness), min(richness), max(richness))
# Make a data frame to draw significance line in boxplot (visually calculated)
rich_nums <- data.frame(a = c(1.15,1.15,1.85,1.85), b = c(1350, 1400, 1400, 1350)) # WholePart vs WholeFree
rich_distribution_plot <-
wide_div_meta_df %>%
ggplot(aes(y = richness, x = fraction)) +
scale_fill_manual(values = fraction_colors) +
geom_jitter(size = 3, aes(fill = fraction, shape = season), width = 0.2) +
geom_boxplot(alpha = 0.5, outlier.shape = NA, aes(fill = fraction)) +
scale_y_continuous(limits = c(150,1500), breaks = seq(from = 0, to =1500, by = 300)) +
labs(y = expression({}^0*italic(D)),
x = "Fraction") +
scale_shape_manual(values = season_shapes) +
geom_path(data = rich_nums, aes(x = a, y = b), linetype = 1, color = "#424645") +
annotate("text", x=1.5, y=1500, size = 8, color = "#424645", label= paste("***"), angle = 90) +
annotate("text", x=1.5, y=1150, size = 4, color = "#424645",
label= paste("p =", round(rich_fraction_wilcox$p.value, digits = 3))) +
theme(legend.position = "none",# axis.title.y = element_blank(),
axis.title.x = element_blank(), axis.text.x = element_blank()) +
coord_flip()
################ Richness vs Community-wide (Per-Liter) Production
## 1. Extract the R2 and p-value from the linear model:
lm_lab_perliter_rich_PA <- paste("atop(R^2 ==", round(summary(lm_prod_vs_rich_PA)$adj.r.squared, digits = 2), ",",
"p ==", round(unname(fig3_adjusted_pvals[1]), digits = 3), ")")
## 2. Plot Richness vs Community-wide (Per-Liter) Production
prod_vs_rich_plot <-
wide_div_meta_df %>%
# Fetch the standard error from diversity measure to plot error bars
left_join(filter(div_iNEXT, Diversity == "Species richness"), by = "norep_filter_name") %>%
rename(se_iNEXT ="s.e.") %>%
ggplot(aes(x=richness, y=frac_bacprod)) +
geom_errorbarh(aes(xmin = richness - se_iNEXT, xmax = richness + se_iNEXT,
color = fraction), alpha = 0.7) + # X-axis errorbars
geom_errorbar(aes(ymin = frac_bacprod - SD_frac_bacprod, ymax = frac_bacprod + SD_frac_bacprod,
color = fraction)) + # Y-axis errorbars
geom_point(size = 3.5, color = "black", aes(fill = fraction, shape = season)) +
scale_color_manual(values = fraction_colors) +
scale_fill_manual(values = fraction_colors) +
scale_shape_manual(values = season_shapes) +
labs(x = expression({}^0*italic(D)),
y = expression(atop("Community Production", "(μgC/L/day)"))) +
geom_smooth(data=filter(wide_div_meta_df, fraction == "Particle"),
method='lm', color = "#FF6600", fill = "#FF6600") +
scale_x_continuous(limits = c(150,1500), breaks = seq(from = 0, to =1500, by = 300)) +
scale_y_continuous(limits = c(-5, 75), breaks = seq(0, 75, by = 15)) +
# Add the R2 and p-value to the plot
annotate("text", x=1200, y=50, label=lm_lab_perliter_rich_PA, parse = TRUE, color = "#FF6600", size = 4) +
theme(legend.position = "none") # axis.title.x = element_blank(), axis.text.x = element_blank()
# Summary stats
summary(lm(frac_bacprod ~ richness, data = filter(wide_div_meta_df, fraction == "Particle")))
# WITHOUT THE TWO HIGH POINTS
summary(lm(frac_bacprod ~ richness, data = filter(wide_div_meta_df, fraction == "Particle" & richness < 1000)))
################ Richness vs Per Capita (Per-Cell) Production
## 1. Extract the R2 and p-value from the linear model:
lm_lab_percell_rich_PA <- paste("atop(R^2 ==", round(summary(lm_percell_prod_vs_rich_PA)$adj.r.squared, digits = 2), ",",
"p ==", round(unname(fig3_adjusted_pvals[2]), digits = 3), ")")
## 2. Plot Richness vs Per Capita (Per-Cell) Production
percell_prod_vs_rich_plot <-
wide_div_meta_df %>%
# Fetch the standard error from diversity measure to plot error bars
left_join(filter(div_iNEXT, Diversity == "Species richness"), by = "norep_filter_name") %>%
rename(se_iNEXT ="s.e.") %>%
ggplot(aes(x=richness, y=log10(fracprod_per_cell_noinf))) +
geom_errorbarh(aes(xmin = richness - se_iNEXT, xmax = richness + se_iNEXT,
color = fraction), alpha = 0.7) + # X-axis errorbars
geom_point(size = 3.5, color = "black", aes(fill = fraction, shape = season)) +
scale_color_manual(values = fraction_colors) +
scale_fill_manual(values = fraction_colors) +
scale_shape_manual(values = season_shapes) +
labs(x = expression({}^0*italic(D)),
y = expression(atop(log[10]*"(Per-Capita Production)", "(μgC/cell/day)"))) +
geom_smooth(data=filter(wide_div_meta_df, fraction == "Particle"),
method='lm', color = "#FF6600", fill = "#FF6600") +
scale_x_continuous(limits = c(150,1500), breaks = seq(from = 0, to =1500, by = 300)) +
scale_y_continuous(limits = c(-8.5,-5), breaks = seq(from = -8, to =-5, by = 1)) +
#scale_y_continuous(limits = c(-8e-7,5e-6), breaks = seq(from = 0, to = 6e-7, by = 3e-7)) +
# Add the R2 and p-value to the plot
annotate("text", x=1200, y=-7.5, label=lm_lab_percell_rich_PA, parse = TRUE, color = "#FF6600", size = 4) +
theme(legend.title = element_blank(), legend.position ="bottom",
legend.text = element_text(size = 14))
# Summary stats
summary(lm(log10(fracprod_per_cell_noinf) ~ richness, data = filter(wide_div_meta_df, fraction == "Particle")))
# WITHOUT THE TWO HIGH POINTS
summary(lm(log10(fracprod_per_cell_noinf) ~ richness, data = filter(wide_div_meta_df, fraction == "Particle" & richness < 1000)))
######################################################### 2D = SIMPSON DIVERSITY (INVERSE SIMPSON)
######################################################### 2D = SIMPSON DIVERSITY (INVERSE SIMPSON)
invsimps_fraction_wilcox <- wilcox.test(simpson ~ fraction, data = wide_div_meta_df)
invsimps_fraction_wilcox
wide_div_meta_df %>%
group_by(fraction) %>%
summarize(mean(simpson), sd(simpson), min(simpson), max(simpson))
# Make a data frame to draw significance line in boxplot (visually calculated)
invsimps_nums <- data.frame(a = c(1.15,1.15,1.85,1.85), b = c(83,85,85,83)) # WholePart vs WholeFree
invsimps_distribution_plot <-
wide_div_meta_df %>%
ggplot(aes(y = simpson, x = fraction)) +
scale_fill_manual(values = fraction_colors) +
scale_shape_manual(values = season_shapes) +
geom_jitter(size = 3, aes(fill = fraction, shape = season), width = 0.2) +
geom_boxplot(alpha = 0.5, outlier.shape = NA, aes(fill = fraction)) +
scale_y_continuous(limits = c(0,85), breaks = seq(from = 0, to = 85, by = 20)) +
labs(y = expression({}^2*italic(D)),
x = "Fraction") +
geom_path(data = invsimps_nums, aes(x = a, y = b), linetype = 1, color = "#424645") +
annotate("text", x=1.5, y=80, size = 4, color = "#424645", label= "NS") +
theme(legend.position = "none", #axis.title.y = element_blank(),
axis.title.x = element_blank(), axis.text.x = element_blank()) +
coord_flip()
################ Inverse Simpson vs Community-wide (Per-Liter) Production
## 1. Extract the R2 and p-value from the linear model:
lm_lab_perliter_invsimps_PA <- paste("atop(R^2 ==", round(summary(lm_prod_vs_invsimps_PA)$adj.r.squared, digits = 2), ",",
"p ==", round(unname(fig3_adjusted_pvals[3]), digits = 3), ")")
## 2. Plot Inverse Simpson vs Community-wide (Per-Liter) Production
prod_vs_invsimps_plot <-
wide_div_meta_df %>%
# Fetch the standard error from diversity measure to plot error bars
left_join(filter(div_iNEXT, Diversity == "Simpson diversity"), by = "norep_filter_name") %>%
rename(se_iNEXT ="s.e.") %>%
ggplot(aes(x=simpson, y=frac_bacprod)) +
geom_errorbarh(aes(xmin = simpson - se_iNEXT, xmax = simpson + se_iNEXT,
color = fraction), alpha = 0.7) + # X-axis errorbars
geom_errorbar(aes(ymin = frac_bacprod - SD_frac_bacprod, ymax = frac_bacprod + SD_frac_bacprod, color = fraction)) + # Y-axis errorbars
geom_point(size = 3.5, color = "black", aes(fill = fraction, shape = season)) +
scale_color_manual(values = fraction_colors) +
scale_fill_manual(values = fraction_colors) +
scale_shape_manual(values = season_shapes) +
labs(x = expression({}^2*italic(D)),
y = expression(atop("Community Production", "(μgC/L/day)"))) +
geom_smooth(data=filter(wide_div_meta_df, fraction == "Particle"), method='lm', color = "#FF6600", fill = "#FF6600") +
scale_x_continuous(limits = c(0,85), breaks = seq(from = 0, to = 85, by = 20)) +
scale_y_continuous(limits = c(-5, 75), breaks = seq(0, 75, by = 15)) +
# Add the R2 and p-value to the plot
annotate("text", x=70, y=45, label=lm_lab_perliter_invsimps_PA, parse = TRUE, color = "#FF6600", size = 4) +
theme(legend.position = "none") #axis.title.x = element_blank(), axis.text.x = element_blank()
# Summary stats
summary(lm(frac_bacprod ~ simpson, data = filter(wide_div_meta_df, fraction == "Particle")))
# WITHOUT THE TWO HIGH POINTS
summary(lm(frac_bacprod ~ simpson, data = filter(wide_div_meta_df, fraction == "Particle" & simpson < 70)))
################ Inverse Simpson vs Per Capitra (Per-Cell) Production
## 1. Extract the R2 and p-value from the linear model:
lm_lab_percell_invsimps_PA <- paste("atop(R^2 ==", round(summary(lm_percell_prod_vs_invsimps_PA)$adj.r.squared, digits = 2), ",",
"p ==", round(unname(fig3_adjusted_pvals[4]), digits = 3), ")")
## 2. Plot Inverse Simpson vs Per Capitra (Per-Cell) Production
percell_prod_vs_invsimps_plot <-
wide_div_meta_df %>%
# Fetch the standard error from diversity measure to plot error bars
left_join(filter(div_iNEXT, Diversity == "Simpson diversity"), by = "norep_filter_name") %>%
rename(se_iNEXT ="s.e.") %>%
ggplot(aes(x=simpson, y=log10(fracprod_per_cell_noinf))) +
geom_errorbarh(aes(xmin = simpson - se_iNEXT, xmax = simpson + se_iNEXT,
color = fraction), alpha = 0.7) + # X-axis errorbars
geom_point(size = 3.5, color = "black", aes(shape = season, fill = fraction)) +
scale_color_manual(values = fraction_colors, guide = TRUE) +
scale_fill_manual(values = fraction_colors, guide = FALSE) +
scale_shape_manual(values = season_shapes) +
labs(x = expression({}^2*italic(D)),
y = expression(atop(log[10]*"(Per-Capita Production)", "(μgC/cell/day)"))) +
geom_smooth(data=filter(wide_div_meta_df, fraction == "Particle"), method='lm', color = "#FF6600", fill = "#FF6600") +
scale_x_continuous(limits = c(0,85), breaks = seq(from = 0, to = 85, by = 20)) +
scale_y_continuous(limits = c(-8.5,-5), breaks = seq(from = -8, to =-5, by = 1)) +
# Add the R2 and p-value to the plot
annotate("text", x=70, y=-7.5, label=lm_lab_percell_invsimps_PA, parse = TRUE, color = "#FF6600", size = 4) +
guides(color = guide_legend(override.aes = list(shape = 15))) +
theme(legend.title = element_blank(), legend.position ="bottom",
legend.text = element_text(size = 14))
# Summary stats
summary(lm(log10(fracprod_per_cell_noinf) ~ simpson, data = filter(wide_div_meta_df, fraction == "Particle")))
# WITHOUT THE TWO HIGH POINTS
summary(lm(log10(fracprod_per_cell_noinf) ~ simpson, data = filter(wide_div_meta_df, fraction == "Particle" & simpson < 70)))
```
**Plot figure 3**
```{r Figure-3, fig.width=7, fig.height=6}
# All plots together
fig3_top <- plot_grid(prod_vs_rich_plot + theme(plot.margin = unit(c(0.2,0.2,0.2,0.8), "cm")), # t, r, b, l
prod_vs_invsimps_plot,
percell_prod_vs_rich_plot + theme(legend.position = "none"),
percell_prod_vs_invsimps_plot + theme(legend.position = "none"),
labels = c("A", "B", "C", "D"), ncol = 2, nrow = 2,
rel_heights = c(1, 1), rel_widths = c(1,1),
align = "hv")
# add legend
plot_grid(fig3_top, season_legend,