/
OrchardSup.Rmd
1528 lines (1158 loc) · 57.4 KB
/
OrchardSup.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: 'Orchard Project: Supplementary'
output:
word_document: default
html_document: default
---
#### Colin Brislawn, PNNL, Spring 2017
#### (Includes both 16S and 18S data)
#### About this document
This is an R Markdown document. Markdown is a simple formatting syntax for
authoring HTML, PDF, and MS Word documents. For more details on using R Markdown
see <http://rmarkdown.rstudio.com>.
This project makes use of many packages, especially Phyloseq <https://joey711.github.io/phyloseq/>.
The goal of this document it to provide a comprehensive overview of all methods
used in the paper for visualizing amplicon data.
This document is directly based on the methods used in [Trade-offs between microbiome diversity and productivity in a stratified microbial mat](https://github.com/pnnl/bernstein-2016-productivity-and-diversity). Both projects are a collaboration with Hans Bernstein in 2016-2017.
### Setup:
```{r setup, results="hide"}
library("checkpoint")
library("knitr")
checkpoint("2016-10-01", use.knitr = T)
library("ggplot2")
library("phyloseq")
# How to install phyloseq:
# 1) Let checkpoint() install as much as possible.
# 2) Run: source('http://bioconductor.org/biocLite.R'); biocLite('phyloseq', suppressUpdates = T)
library("RColorBrewer")
library("viridis")
library("scales")
library("cowplot")
library("vegan")
library("dplyr")
library("lubridate")
library("reshape2")
library("ggrepel")
theme_set(theme_bw())
opts_chunk$set(cache=TRUE, dev = c('png'), warning = F)
# This let's our special characters like ‰ be saved to out pdfs:
pdf.options(encoding = "MacRoman.enc")
# Not sure how well this works cross platforms.
```
```{r setup-2, cache=F}
packageVersion('phyloseq')
set.seed(711)
```
The function `set.seed()` is used here to provide a reproducible starting point
for random number generation. Random sampling is used throughout this document,
from `phyloseq::rarefy_even_depth()` to `vegan::adonis()`, and small changes to
the order in which sampling is performed could change the results.
### Import data
Our work here will focus on two amplicon data sets. One from the 16S gene, the
other from the 18S gene. Because these amplicons came from different primers and
are expected to target different genes (of different evolutionary history,
length, complexity, etc) they will be analyzed separately. (This also makes the
stats simpler.)
```{r importdata}
no_meta <- import_biom(file.path('../data/16S_otus_vsearch/otu_table_w_tax.biom')
#,file.path('../16S/otus_vsearch/rep_set.tre')
)
meta <- import_qiime_sample_data(file.path('../metadata/generated-meta.tsv'))
full16s <- merge_phyloseq(meta, no_meta)
full16s
no_meta_18s <- import_biom(file.path('../data/18S_otus_vsearch/otu_table_w_tax.biom'))
full18s <- merge_phyloseq(meta, no_meta_18s)
full18s
```
### Explore metadata
Let's take a look at columns in the metadata file.
**Make major edits to the metadata using the `generate-metadata.Rmd` file.** This
file focuses on downstream analysis, while metadata wrangling should have
be completed already.
```{r meta, results="hide"}
# Let's use 16S, as it's our main focus, and has more samples.
meta <- sample_data(full16s)
meta.n_unique <- rapply(meta, function(x) length(table(x)))
# The pairwise interesting factors
meta.n_unique[meta.n_unique == 2]
# Other potentially interesting factors
meta.n_unique[meta.n_unique > 2 & meta.n_unique < max(meta.n_unique)]
# Main study design:
# 4 Substrates every 6 hours for 48 hours
table(meta$Time..H., meta$Substrate)
meta$rep. <- factor(meta$rep.)
# Reorder levels of Substrate
levels(meta$Substrate)
meta$Substrate <- factor(meta$Substrate, levels = c("13C DIC", "13C Acetate", "13C Glucose", "Control", "Native Mat"))
levels(meta$Substrate)
# Also, rename levels of Substrate
levels(meta$Substrate) <- c("DIC", "Acetate", "Glucose", "Control", "Native Mat")
levels(meta$Substrate)
# Fix import of standard timestamp format
meta$collection_timestamp <- ymd_hms(meta$collection_timestamp)
# Let's keep Time..H. numeric
#meta$Time..H. <- factor(meta$Time..H.)
sample_data(full16s) <- meta
sample_data(full18s) <- meta
```
## Environmental Metadata
This study includes measurements of several environmental variables over 48 hours.
Understanding how these vary over time, let us focus on interesting changes.
```{r meta-graphs, fig.height=7, fig.show="hide", results="hide", warning=F}
table(meta$Time..H., meta$Substrate)
head(meta)
#meta.melt <- meta
meta.melt = melt(meta, measure.vars = c("SKNT.mph", "SOLR.W.m.m", "PREC.in", "STEN.centibar", "TMP..C.", "fin_diff_Ave_d13C.organic"))
head(meta.melt)
meta.gg <- ggplot(meta.melt, aes(Time..H., value, color = Time..H.))
meta.gg <- meta.gg +
#geom_boxplot(color = "gray") + #, outlier.size = 0) +
geom_jitter(width = 0.1) +
facet_grid(facets = variable~., scales = "free_y") +
labs(x = "Time (h)", title = "Environmental factors") +
#v +
theme(legend.position = "none",
strip.background = element_blank(),
axis.title.y = element_blank())
meta.gg
```
Only substrate, light, and time would realistically effect the sample.
Let's check out how the measured isotopes changed...
```{r meta-specific, fig.width=10, results="hide"}
# Sunlight colormap
pl.c <- scale_color_viridis(option = "C", discrete = F, begin = .1, end = 1)
head(meta)
table(meta$Substrate)
meta.melt2 = melt(meta, measure.vars = c("Ave_d13C", "Ave_.C", "Ave_.C.organic", "Ave_d13C.organic", "diff_Ave_d13C.organic", "fin_diff_Ave_d13C.organic"))
head(meta.melt2)
meta.gg2 <- ggplot(meta.melt2, aes(Time..H., value, color = SOLR.W.m.m))
meta.gg2 <- meta.gg2 +
#geom_boxplot(color = "gray") + #, outlier.size = 0) +
geom_jitter(width = 0.1) +
facet_grid(facets = variable~Substrate, scales = "free_y", switch = "y") +
labs(x = "Time (h)", title = "Isotopes and Primary Productivity") +
pl.c +
theme(legend.position = "right",
strip.background = element_blank(),
axis.title.y = element_blank()
#, plot.margin=unit(c(5,5,-25,5), units = "pt")
)
meta.gg2
```
```{r fig1-meta, results="hide", fig.show="hide"}
fig1.a <- ggplot(meta, aes(Time..H., SOLR.W.m.m, color = SOLR.W.m.m))
fig1.a <- fig1.a + geom_line(alpha = 1, color="gray80") + geom_point(size = 1.5) +
#labs(y = "Ii (Wm^-2)") +
facet_grid(PREC.in~.) + # This is a single 'dummy' facet so plot_grid() will align it
scale_color_viridis(option = "C", end = .90) +
labs(x = "Time (h)", y =
#expression(atop("Irradiance", "("~ Wm^{-2}~ ")")) # two lines
expression("Irradiance ("~Wm^{-2}~")") # one line
) +
scale_x_continuous(breaks = c(0, 24, 48), limits = c(0, 48)) +
theme(
#axis.title.y = element_text(angle = 0, vjust = .5),
legend.position = "none",
strip.text = element_blank(), strip.background = element_blank() # remove 'dummy' facet
)
fig1.a
# only use key Substrates
meta.small <- subset(meta, Substrate %in% c("Glucose", "Acetate", "DIC"))
fig1.b <- ggplot(meta.small, aes(Time..H., fin_diff_Ave_d13C.organic, color = Substrate))
fig1.b <- fig1.b +
geom_abline(slope = 0, color = "gray66") +
geom_line(alpha = .4) +
geom_point() +
geom_errorbar(aes(ymax = (fin_diff_Ave_d13C.organic + fin_diff_Stdev_d13C.organic), ymin = (fin_diff_Ave_d13C.organic - fin_diff_Stdev_d13C.organic)), width = 0) +
# Note that we have two error bars. diff_Stdev and diff_Stdev_hourly
scale_color_brewer(palette = "Set2") +
facet_grid(Substrate~., scales = "free_y") +
labs(x = "Time (h)", y =
expression("Productivity: " ~ Delta~delta^13~C / Delta ~t ~" (‰"~ h^-1~")") # note this uses the ‰ 'Per_mille' sign
) +
scale_x_continuous(breaks = c(0, 24, 48), limits = c(0, 48)) +
#geom_text(aes(5, -20, label=Substrate), hjust = 0) +
theme(strip.background = element_blank(),
legend.position = "none")
fig1.b
```
#### Figure 1, a b
This figure could be rendered at 5.5 vs 2.4, to fit figure without scaling.
Here, I'm exporting at 6x3, with the expectation that it will be scaled down when composing the figure.
```{r figure-1, fig.height=6, fig.width=3, cache=F}
plot_grid(fig1.a, fig1.b, align = "v", rel_heights = c(1.4,3), ncol = 1, labels = c("A", "B"))
# this should match the height of fig1-cd and their widths should add to 183
ggsave('fig1-ab.pdf', path = "./figures/", units = "mm", width = 61, height = 122, scale = 1.2)
```
#### Sup Figure 1: productivity vs irradiance
Note: This graph does shows a single panel because
only a single measurement of carbon uptake was made.
```{r figure-prod-vs-I, fig.height=4.5, fig.width=3.5, results="hide"}
# Let's see if we can add slopes and p-values to these graphs
# See https://stackoverflow.com/questions/17022553/adding-r2-on-graph-with-facets
# Example data for testing function
df <- data.frame(meta.small[meta.small$Substrate == "Glucose", ])
head(df)
dim(df)
lm_eqn_lighvsc = function(df){
pearson <- cor.test(df$SOLR.W.m.m, df$fin_diff_Ave_d13C.organic, method = "pearson", conf.level = 0.95)
pearson
pearson$p.value # this p-value matches the one from summary(lm())$coefficients
pearson$estimate
eq <- substitute(
# This text parsing here is poor.
#atop("slope ="~slope, "p-value ="~pv), # Two lines
#~~R^2~"="~r2~", p-value "~pv, # with R^2
"r ="~r~"p-value"~pv, # One line
list(
r = paste(signif(pearson$estimate, digits = 3), ",", sep = ""),
pv = if(pearson$p.value <= 0.001) pv = "< 0.001" else pv = paste("= ", sprintf(fmt = "%.3f", pearson$p.value), sep = "")
)
)
as.character(as.expression(eq))
}
# Make a matching data frame with these calculated values
# This is based on the stackoverflow answer, and on the Bile Acids graphs
# See Lactobacillus acidophilus disrupts multispecies synthesis of a secondary bile acid ursocholate
# Hans C. Bernstein, PNNL, 2017
eqns <- by(data.frame(meta.small), INDICES = list(meta.small$Substrate), lm_eqn_lighvsc)
#eqns
df2 <- data.frame(eq = c(eqns),
Substrate = c("DIC", "Acetate", "Glucose"),
graphx = c(350, 350, 250),
graphy = c(-1.8, 60, 90))
df2
fig.pvi <- ggplot(meta.small, aes(SOLR.W.m.m, fin_diff_Ave_d13C.organic, color = Substrate))
fig.pvi <- fig.pvi +
geom_abline(slope = 0, color = "gray66") +
geom_point() +
geom_smooth(method = "lm") +
geom_errorbar(aes(ymax = (fin_diff_Ave_d13C.organic + fin_diff_Stdev_d13C.organic), ymin = (fin_diff_Ave_d13C.organic - fin_diff_Stdev_d13C.organic)), width = 0) +
# Note that we have two error bars. diff_Stdev and diff_Stdev_hourly
scale_color_brewer(palette = "Set2") + # use with color = Substrate
#scale_color_viridis(option = "C", end = .90) + # use with color = SOLR.W.m.m
facet_grid(Substrate~., scales = "free_y") +
geom_text(data = df2, aes(x = graphx, y = graphy, label = eq), color = '#777777', parse = TRUE) +
labs(x = expression("Irradiance ("~ Wm^{-2}~ ")")
,y=expression("Productivity: " ~ Delta~delta^13~C / Delta ~t ~" (‰"~ h^-1~")")
) +
#geom_text(aes(5, -20, label=Substrate), hjust = 0) +
theme(strip.background = element_blank(),
legend.position = "none")
fig.pvi
ggsave('fig-sup.pdf', path = "./figures/", units = "mm", width = 89, height = 120, scale = 1)
```
## Preprocess
Remove all non-bacteria microbes, along with OTUs annotated as chloroplasts or
mitochondria.
Inspect sample sizes and rarefy....
Also create cohort of Time > 0 samples. We may not want to include the initial
three samples.
#### 16S
```{r preprocess16s, fig.height=3, fig.show="hide", results="hide"}
filtered16s <- subset_taxa(full16s, Rank1 == "k__Bacteria")
ntaxa(filtered16s) / ntaxa(full16s)
sum(taxa_sums(filtered16s)) / sum(taxa_sums(full16s))
# Why are we losing so many reads?
nonbacteria.16s <- subset_taxa(full16s, Rank1 != "k__Bacteria")
plot_bar(nonbacteria.16s, fill = "Rank1")
# Not NOT Archaea. It's mostly unnown microbes...
plot(sort(taxa_sums(nonbacteria.16s)))
head(sort(taxa_sums(nonbacteria.16s), T))
# ... Two unknown microbes: OTU_4 and OTU_5
# After aligning out reads to Hot Lake data from Jen, we got <70% match for OTU_5, but
# 100% match for OTU_4 with this taxonomy
#CA_scaffold_065971 unbinned 83.2353 366.4339484 216.1214765 190.3818837 165.2089407 189.8963216 Bacteria;Chloroflexi;Anaerolineae;Anaerolineales;Anaerolineaceae;uncultured;
# Let's fix it, with a greengenes-like name
tax_table(full16s)["OTU_4",]
# tax_table(full16s)["OTU_4",] <- c("Unassigned", NA, NA, NA, NA, NA, NA) # Value from taxonomy assignment
tax_table(full16s)["OTU_4",] <- c("k__Bacteria", "p__Chloroflexi", "c__Anaerolineae",
"o__Anaerolineales", "f__Anaerolineaceae", "g__", "s__")
#k__Bacteria; p__Chloroflexi; c__Anaerolineae; o__Anaerolineales;
# Now that OTU_4 has been fixed, jump back into filtering
filtered16s <- subset_taxa(full16s, Rank1 == "k__Bacteria")
sum(taxa_sums(filtered16s)) / sum(taxa_sums(full16s))
# Looks like OTU_5 still causes us to lose 7% of reads, but that's much better
filtered16s <- subset_taxa(filtered16s, !(Rank5 %in% c("f__mitochondria")))
filtered16s <- subset_taxa(filtered16s, !(Rank3 %in% c("c__Chloroplast")))
ntaxa(filtered16s) / ntaxa(full16s)
sum(taxa_sums(filtered16s)) / sum(taxa_sums(full16s))
# Very few reads are from mitochondria and chloroplast
# Now throw away failed samples and normalize
plot(sort(sample_sums(filtered16s)))
ggplot(sample_data(filtered16s), aes(sample_sums(filtered16s))) + geom_histogram(binwidth = 10000, aes(fill=Date))
ggplot(sample_data(filtered16s), aes(sample_sums(filtered16s))) + geom_histogram(binwidth = 10000, aes(fill=Substrate))
sort(sample_sums(filtered16s))[1:30]
rar.16s <- rarefy_even_depth(filtered16s, sample.size = 22000)
rar.16s
rar.16s.cohort <- subset_samples(rar.16s, Time..H. != 0 & Substrate %in% c("DIC", "Acetate", "Glucose"))
rar.16s.cohort
```
#### 18S
18S is handled similarly, although no taxonomic filtering is used.
```{r preprocess18s, fig.show="hide", results="hide"}
plot(sort(sample_sums(full18s)))
ggplot(sample_data(full18s), aes(sample_sums(full18s))) + geom_histogram(binwidth = 10000, aes(fill=Date))
ggplot(sample_data(full18s), aes(sample_sums(full18s))) + geom_histogram(binwidth = 10000, aes(fill=Substrate))
sort(sample_sums(full18s))[1:30]
rar.18s <- rarefy_even_depth(full18s, sample.size = 22000, rngseed = F, replace = T)
rar.18s
rar.18s.cohort <- subset_samples(rar.18s, Time..H. != 0 & Substrate %in% c("DIC", "Acetate", "Glucose"))
rar.18s.cohort
```
#### Characterize cohorts used in downstream analysis
```{r cohorts-2, include=T}
# All samples from MiSeq
table(sample_data(full16s)$Time..H., sample_data(full16s)$Substrate)
# Samples with good depth
table(sample_data(rar.16s)$Time..H., sample_data(rar.16s)$Substrate)
# Samples used in analysis.
table(sample_data(rar.16s.cohort)$Time..H., sample_data(rar.16s.cohort)$Substrate)
# All samples from MiSeq
table(sample_data(full18s)$Time..H., sample_data(full18s)$Substrate)
# Samples with good depth
table(sample_data(rar.18s)$Time..H., sample_data(rar.18s)$Substrate)
# Samples used in analysis.
table(sample_data(rar.18s.cohort)$Time..H., sample_data(rar.18s.cohort)$Substrate)
```
The main feature is Substrate, varying over hours.
Looks like we lost samples throughout, but have at least one rep for each block
of the study design.
Don't merge now, but maybe merge later for clear graphs.
#### Counts of OTUs and phyla in each data set
```{r counts-of-otus}
rar.16s.cohort %>% taxa_sums %>% sort %>% subset(. > 0) %>% length # number of OTUs
rar.16s.cohort %>% tax_table %>% data.frame %>% select(Rank2) %>% unique %>% dim # number of Phyla
rar.18s.cohort %>% taxa_sums %>% sort %>% subset(. > 0) %>% length
rar.18s.cohort %>% tax_table %>% data.frame %>% select(Rank2) %>% unique %>% dim # number of Phyla
```
Due to the rarefaction step, the counts of OTU change slightly. So lets just pull these numbers from the full cohort.
```{r counts-of-otus-full}
full16s %>% taxa_sums %>% sort %>% subset(. > 0) %>% length # number of OTUs
full16s %>% tax_table %>% data.frame %>% select(Rank2) %>% unique %>% dim # number of Phyla
full18s %>% taxa_sums %>% sort %>% subset(. > 0) %>% length
full18s %>% tax_table %>% data.frame %>% select(Rank2) %>% unique %>% dim # number of Phyla
```
# Plots
I'll use rarefied data, for consistency.
## Abundance plots
There will be a matching set of relative abundance plots, for each amplicon type.
Taxa abundances will be used twice. First for stacked bar plots in figure 1,
then again for input to bi-plot. The difference is that we will be merging reps
before graphing taxa in the barplots in Figure 1.
```{r ra.graphs-prep, results="hide"}
# make a numeric time factor
sample_data(rar.16s.cohort)$Time..H. <- as.numeric(sample_data(rar.16s.cohort)$Time..H.)
sample_data(rar.18s.cohort)$Time..H. <- as.numeric(sample_data(rar.18s.cohort)$Time..H.)
# Change rep name
sample_data(rar.16s.cohort)$newrep <- paste(sample_data(rar.16s.cohort)$Substrate, sample_data(rar.16s.cohort)$timepoint)
sample_data(rar.18s.cohort)$newrep <- paste(sample_data(rar.18s.cohort)$Substrate, sample_data(rar.18s.cohort)$timepoint)
# Merge Samples,
rar.16s.cohort.merged <- merge_samples(rar.16s.cohort, c("newrep"))
rar.18s.cohort.merged <- merge_samples(rar.18s.cohort, c("newrep"))
# Fix names after merge
sample_data(rar.16s.cohort.merged)$Substrate <-
factor((sample_data(rar.16s.cohort.merged)$Substrate), labels = c("DIC", "Acetate", "Glucose"))
sample_data(rar.18s.cohort.merged)$Substrate <-
factor((sample_data(rar.18s.cohort.merged)$Substrate), labels = c("DIC", "Acetate", "Glucose"))
# Check that this works
#head(sample_data(rar.16s.cohort.merged))
#merge OTUs, then transform to RA
rar.16s.cohort.merged5 <- tax_glom(rar.16s.cohort.merged, taxrank = "Rank5")
rar.16s.cohort.merged5 <- transform_sample_counts(rar.16s.cohort.merged5, function(x) x / sum(x))
rar.18s.cohort.merged5 <- tax_glom(rar.18s.cohort.merged, taxrank = "Rank5")
rar.18s.cohort.merged5 <- transform_sample_counts(rar.18s.cohort.merged5, function(x) x / sum(x))
rar.16s.cohort.merged4 <- tax_glom(rar.16s.cohort.merged5, taxrank = "Rank4")
rar.16s.cohort.merged4 <- transform_sample_counts(rar.16s.cohort.merged4, function(x) x / sum(x))
rar.18s.cohort.merged4 <- tax_glom(rar.18s.cohort.merged5, taxrank = "Rank4")
rar.18s.cohort.merged4 <- transform_sample_counts(rar.18s.cohort.merged4, function(x) x / sum(x))
rar.16s.cohort.merged3 <- tax_glom(rar.16s.cohort.merged4, taxrank = "Rank3")
rar.16s.cohort.merged3 <- transform_sample_counts(rar.16s.cohort.merged3, function(x) x / sum(x))
rar.18s.cohort.merged3 <- tax_glom(rar.18s.cohort.merged4, taxrank = "Rank3")
rar.18s.cohort.merged3 <- transform_sample_counts(rar.18s.cohort.merged3, function(x) x / sum(x))
# Improve taxa names
tax_table(rar.16s.cohort.merged5)[,"Rank5"] <- gsub("f__", "", tax_table(rar.16s.cohort.merged5)[,"Rank5"], fixed = T)
tax_table(rar.18s.cohort.merged5)[,"Rank5"] <- gsub("D.*_", "", tax_table(rar.18s.cohort.merged5)[,"Rank5"])
tax_table(rar.16s.cohort.merged4)[,"Rank4"] <- gsub("o__", "", tax_table(rar.16s.cohort.merged4)[,"Rank4"], fixed = T)
tax_table(rar.18s.cohort.merged4)[,"Rank4"] <- gsub("D_3__", "", tax_table(rar.18s.cohort.merged4)[,"Rank4"], fixed = T)
tax_table(rar.16s.cohort.merged3)[,"Rank3"] <- gsub("c__", "", tax_table(rar.16s.cohort.merged3)[,"Rank3"], fixed = T)
tax_table(rar.18s.cohort.merged3)[,"Rank3"] <- gsub("D_2__", "", tax_table(rar.18s.cohort.merged3)[,"Rank3"], fixed = T)
```
```{r ra.graphs-ggplot, fig.width=9, fig.show="hide", results="hide"}
# Pick level to use:
rar.16s.cohort.merged <- rar.16s.cohort.merged3
rar.18s.cohort.merged <- rar.18s.cohort.merged3
# Also remove [brackets] from Greengenes candidate taxa
tax_table(rar.16s.cohort.merged)[,"Rank3"] <- gsub("[][]", "", tax_table(rar.16s.cohort.merged)[,"Rank3"], fixed = F)
# Take top taxa
rar.16s.cohort.merged.top <- prune_taxa(names(sort(taxa_sums(rar.16s.cohort.merged), TRUE))[0:10], rar.16s.cohort.merged)
rar.16s.cohort.merged.top
sum(taxa_sums(rar.16s.cohort.merged.top)) / sum(taxa_sums(rar.16s.cohort.merged))
# Which 3 taxa do we lose if we take the top 7 taxa?
#sort(taxa_sums(rar.16s.cohort.merged.top))/nsamples(rar.16s.cohort.merged.top)
#tax_table(rar.16s.cohort.merged.top)[c("OTU_49", "OTU_25", "OTU_12")]
# how much of the full community are these three taxa?
psmelt(rar.16s.cohort.merged.top) %>% subset(OTU %in% c("OTU_49", "OTU_25", "OTU_12")) %>% select(Abundance) %>% sum()
# by dropping 8,9,10, we lose ~ 4% of full population. Let's try it.
rar.16s.cohort.merged.top <- prune_taxa(names(sort(taxa_sums(rar.16s.cohort.merged), TRUE))[0:7], rar.16s.cohort.merged)
#psmelt(rar.16s.cohort.merged.top) %>% head
fig1.c <- ggplot(psmelt(rar.16s.cohort.merged.top) %>% arrange(desc(Rank3)), aes(x = Time..H., y = Abundance, fill = Rank3)) +
geom_bar(stat = "identity") +
facet_grid(~Substrate) +
scale_fill_viridis(discrete = T, begin = .1, end = .9, name = "16S Taxa") +
labs(x = "Time (h)") +
scale_x_continuous(breaks = c(6, 24, 48)) +
scale_y_continuous(limits = c(0, 1)) +
theme(axis.text.x = element_text(angle = 0, hjust = .5),
#legend.justification = c("left", "top"), #cowplot ignores this
# legend.margin = margin(3,3,3,3),
strip.background = element_blank())
fig1.c
# Take top taxa
rar.18s.cohort.merged.top <- prune_taxa(names(sort(taxa_sums(rar.18s.cohort.merged), TRUE))[0:10], rar.18s.cohort.merged)
rar.18s.cohort.merged.top
sum(taxa_sums(rar.18s.cohort.merged.top)) / sum(taxa_sums(rar.18s.cohort.merged))
# Which 3 taxa do we lose if we take the top 7 taxa?
#sort(taxa_sums(rar.18s.cohort.merged.top))/nsamples(rar.18s.cohort.merged.top)
#tax_table(rar.18s.cohort.merged.top)[c("OTU_160", "OTU_203", "OTU_154")]
# how much of the full community are these three taxa?
psmelt(rar.18s.cohort.merged.top) %>% subset(OTU %in% c("OTU_160", "OTU_203", "OTU_154")) %>% select(Abundance) %>% sum()
# ONLY 0.5%. OK, let's drop them.
rar.18s.cohort.merged.top <- prune_taxa(names(sort(taxa_sums(rar.18s.cohort.merged), TRUE))[0:7], rar.18s.cohort.merged)
fig1.d <- ggplot(psmelt(rar.18s.cohort.merged.top) %>% arrange(desc(Rank3)), aes(x = Time..H., y = Abundance, fill = Rank3)) +
geom_bar(stat = "identity") +
facet_grid(~Substrate) +
scale_fill_viridis(discrete = T, option = "A", begin = .25, direction = -1, name = "18S Taxa") +
labs(x = "Time (h)") +
scale_x_continuous(breaks = c(6, 24, 48)) +
scale_y_continuous(limits = c(0, 1)) +
theme(axis.text.x = element_text(angle = 0, hjust = .5),
#legend.justification = c("left", "top"), # cowplot ignores this
# legend.margin = margin(0,0,0,0),
strip.background = element_blank())
fig1.d
```
#### Figure 1, c d
This figure could be rendered at 5.5 vs 4.8, to fit figure without scaling.
Here, I'm exporting at 6x6, with the expectation that it will be scaled down when composing the figure.
```{r figure-1-c-d, fig.height=6, fig.width=6, cache=F}
plot_grid(fig1.c, fig1.d, align = "v", ncol = 1, labels = c("C", "D"))
# hight should match fig1-ab
# width of both should add up to 183
ggsave('fig1-cd.pdf', path = "./figures/", units = "mm", width = 122, height = 122, scale = 1.4)
```
## Beta Diversity
Usually, UniFrac distances are used to characterize beta diversity.
Because I'm not confident of the intricacies of building ML trees from an MSA
made from the 18S amplicon, I'll use Bray-Curtis dissimilarities for everything.
Beta diversity is explored later using the biplot, but here we will be using to
access the uniformity of the mat and our biological replicates.
```{r beta-colors, fig.show="hide", results="hide", eval=F, include=F}
bray.16s = ordinate(rar.16s.cohort, method = "PCoA", distance = "bray")
# Let's start with the same color maps as on the Founders species paper.
# We have chosen to use the darker part of viridis and the lighter part of plasma.
v <- scale_color_viridis(discrete = T, direction = -1, begin = 0, end = 0.9)
v.c <- scale_color_viridis(discrete = F, direction = -1, begin = 0, end = 0.9)
pl <- scale_color_viridis(option = "C", discrete = T, direction = -1, begin = .3, end = 1)
# discreet plasma is used for sunlight, and is defined up above
v.fill <- scale_fill_viridis(discrete = T, direction = -1, begin = 0, end = 0.9)
pl.fill <- scale_fill_viridis(option = "C", discrete = T, direction = -1, begin = 0, end = 1)
rb <- scale_color_brewer(palette = "Spectral")
p.substrate <- plot_ordination(rar.16s.cohort, bray.16s, color="Substrate") + rb
p.substrate
p1 <- plot_ordination(rar.16s.cohort, bray.16s, color="Time..H.") + v.c
p2 <- plot_ordination(rar.16s.cohort, bray.16s, color="SOLR.W.m.m") + pl.c
p3 <- plot_ordination(rar.16s.cohort, bray.16s, color="fin_diff_Ave_d13C.organic") + pl.c
plot_grid(p1, p2, p3, ncol = 1, align = "v")
# Viridis is in vogue, and looks pretty good here.
#
# Viridis: it's a bird, it's a snake, it's a [matplotlib colormap](https://bids.github.io/colormap/)!
# And now it's also [an R package](https://cran.r-project.org/web/packages/viridis/index.html).
#
# Using the "Spectral" color brewer colormap for substrate works well.
```
This question is related to this analysis:
> How homogenous were the mats regarding the microbial diversity? How did the
> variation in community composition from the samples influence the microcosm
> experiment? Were enough replicates performed to outweigh this effect?
We can explore sources of variation several ways:
1) Compare variation between our technical reps and biologically different samples
2) Look at initial timepoints (T0 and T1) and compare magnitude of difference between samples. (Imperfect, as substrate has already been added.)
```{r beta-variation-native-mat, include=F, eval=F}
# 3) Compare our initial samples of the native mat
#We will build the cohorts we need from the original rarefied data sets.
rar.16s %>% sample_data() %>% select(Substrate) %>% table
rar.16s.native <- subset_samples(rar.16s, Substrate %in% c("Native Mat"))
rar.18s.native <- subset_samples(rar.18s, Substrate %in% c("Native Mat"))
distance(rar.16s.native, "bray")
# These are relatively small.
plot_bar(rar.16s.native, x = "Rank2") + facet_grid(Sample~.)
distance(rar.18s.native, "bray") # Not super useful with a single sample
# This is not super helpful because it does not compare differences withint
# between our microcosms.
```
#### 1) Compare variation between our technical reps and biologically different samples
```{r beta-variation-reps-vs-biology}
df = as(sample_data(rar.16s.cohort), "data.frame")
d = distance(rar.16s.cohort, "bray")
adonis(d ~ Substrate + timepoint + rep., df, permutations = 9999)
df = as(sample_data(rar.18s.cohort), "data.frame")
d = distance(rar.18s.cohort, "bray")
adonis(d ~ Substrate + timepoint + rep., df, permutations = 9999)
```
The measurable effect of the technical rep is negligible compared to the effect of Substrate and timepoint.
#### 2) Look at initial timepoints (T0 and T1) and compare magnitude of difference between samples.
Imperfect, as substrate has already been added.
Often in this analysis, the pairwise beta diversity matrix is used as input to an ordination.
In this case, I'm going to look at the distribution of Bray–Curtis dissimilarities directly.
```{r beta-variation-tzero, fig.width=3}
rar.16s %>% sample_data() %>% select(timepoint) %>% table
#bray.16s.zero = ordinate(rar.16s.zero, method = "PCoA", distance = "bray")
#plot_ordination(rar.16s.zero, bray.16s.zero, color="Substrate", shape = "timepoint") + geom_line()
# 16s
rar.16s.zero <- subset_samples(rar.16s, timepoint %in% c("T0", "T1"))
distance(rar.16s.zero, "bray") %>% as.list %>% unlist() %>% summary()
distance(rar.16s.zero, "bray") %>% as.list %>% as.data.frame() %>% melt() %>%
ggplot(mapping = aes(x = "16S samples at T1\n(6 hours)", y = value)) +
labs(y = "Bray–Curtis dissimilarities") +
geom_violin() + geom_boxplot() + geom_jitter(width = .2)
# 18s
rar.18s.zero <- subset_samples(rar.18s, timepoint %in% c("T0", "T1"))
distance(rar.18s.zero, "bray") %>% as.list %>% unlist() %>% summary()
distance(rar.18s.zero, "bray") %>% as.list %>% as.data.frame() %>% melt() %>%
ggplot(mapping = aes(x = "18S samples at T1\n(6 hours)", y = value)) +
labs(y = "Bray–Curtis dissimilarities") +
geom_violin() + geom_boxplot() + geom_jitter(width = .2)
```
So even after 6 hours of incubation, the 16s community has just started to respond to substrate, while the 18S is much more variable.
```{r adonistest, include=F, eval=F}
# The strata= argument could help with time series data.
df = as(sample_data(rar.16s.cohort), "data.frame")
d = distance(rar.16s.cohort, "bray")
cohort.adonis = adonis(d ~ Substrate + SOLR.W.m.m + Time..H., df)
cohort.adonis
df = as(sample_data(rar.18s.cohort), "data.frame")
d = distance(rar.18s.cohort, "bray")
cohort.adonis = adonis(d ~ Substrate + SOLR.W.m.m + Time..H., df)
cohort.adonis
```
## Alpha diversity
This function extends phyloseq::estimate_richness() function by
implementing two evenness metrics.
See this PR <https://github.com/joey711/phyloseq/pull/575>
```{r extend-alpha-diversity, results="hide"}
estimate_richness_mod <- function(physeq, split=TRUE, measures=NULL){
if( !any(otu_table(physeq)==1) ){
# Check for singletons, and then warning if they are missing.
# These metrics only really meaningful if singletons are included.
warning(
"The data you have provided does not have\n",
"any singletons. This is highly suspicious. Results of richness\n",
"estimates (for example) are probably unreliable, or wrong, if you have already\n",
"trimmed low-abundance taxa from the data.\n",
"\n",
"We recommended that you find the un-trimmed data and retry."
)
}
# If we are not splitting sample-wise, sum the species. Else, enforce orientation.
if( !split ){
OTU <- taxa_sums(physeq)
} else if( split ){
OTU <- as(otu_table(physeq), "matrix")
if( taxa_are_rows(physeq) ){ OTU <- t(OTU) }
}
# Define renaming vector:
renamevec = c("Observed", "Chao1", "ACE", "Shannon", "Pielou", "Simpson", "InvSimpson", "SimpsonE", "Fisher")
names(renamevec) <- c("S.obs", "S.chao1", "S.ACE", "shannon", "pielou", "simpson", "invsimpson", "simpsone", "fisher")
# If measures was not explicitly provided (is NULL), set to all supported methods
if( is.null(measures) ){
measures = as.character(renamevec)
}
# Rename measures if they are in the old-style
if( any(measures %in% names(renamevec)) ){
measures[measures %in% names(renamevec)] <- renamevec[names(renamevec) %in% measures]
}
# Stop with error if no measures are supported
if( !any(measures %in% renamevec) ){
stop("None of the `measures` you provided are supported. Try default `NULL` instead.")
}
# Initialize to NULL
outlist = vector("list")
# Some standard diversity indices
estimRmeas = c("Chao1", "Observed", "ACE")
if( any(estimRmeas %in% measures) ){
outlist <- c(outlist, list(t(data.frame(estimateR(OTU)))))
}
if( "Shannon" %in% measures ){
outlist <- c(outlist, list(shannon = diversity(OTU, index="shannon")))
}
if( "Pielou" %in% measures){
#print("Starting Pielou")
outlist <- c(outlist, list(pielou = diversity(OTU, index = "shannon")/log(estimateR(OTU)["S.obs",])))
}
if( "Simpson" %in% measures ){
outlist <- c(outlist, list(simpson = diversity(OTU, index="simpson")))
}
if( "InvSimpson" %in% measures ){
outlist <- c(outlist, list(invsimpson = diversity(OTU, index="invsimpson")))
}
if( "SimpsonE" %in% measures ){
#print("Starting SimpsonE")
outlist <- c(outlist, list(simpsone = diversity(OTU, index="invsimpson")/estimateR(OTU)["S.obs",]))
}
if( "Fisher" %in% measures ){
fisher = tryCatch(fisher.alpha(OTU, se=TRUE),
warning=function(w){
warning("phyloseq::estimate_richness: Warning in fisher.alpha(). See `?fisher.fit` or ?`fisher.alpha`. Treat fisher results with caution")
suppressWarnings(fisher.alpha(OTU, se=TRUE)[, c("alpha", "se")])
}
)
if(!is.null(dim(fisher))){
colnames(fisher)[1:2] <- c("Fisher", "se.fisher")
outlist <- c(outlist, list(fisher))
} else {
outlist <- c(outlist, Fisher=list(fisher))
}
}
out = do.call("cbind", outlist)
# Rename columns per renamevec
namechange = intersect(colnames(out), names(renamevec))
colnames(out)[colnames(out) %in% namechange] <- renamevec[namechange]
# Final prune to just those columns related to "measures". Use grep.
colkeep = sapply(paste0("(se\\.){0,}", measures), grep, colnames(out), ignore.case=TRUE)
out = out[, sort(unique(unlist(colkeep))), drop=FALSE]
# Make sure that you return a data.frame for reliable performance.
out <- as.data.frame(out)
return(out)
}
```
Now, let's use our modified richness function.
```{r alpha.reshape}
metrics <- c("Observed", "SimpsonE")
rich.16s <- estimate_richness_mod(rar.16s.cohort, measures = metrics)
rich.18s <- estimate_richness_mod(rar.18s.cohort, measures = metrics)
# Rename for graphing
graphnames <- c("Richness", "Evenness")
names(rich.16s) <- graphnames
names(rich.18s) <- graphnames
# merge richness with metadata
DF.16s <- merge(rich.16s, sample_data(rar.16s.cohort), by = 0)
DF.18s <- merge(rich.18s, sample_data(rar.18s.cohort), by = 0)
# melt for graphing
reshapevars <- c("Richness", "Evenness")
mdf.16s = melt(DF.16s, measure.vars = graphnames)
mdf.18s = melt(DF.18s, measure.vars = graphnames)
#head(mdf.16s)
mdf.16s$Time..H.num <- as.numeric(mdf.16s$Time..H.)
mdf.18s$Time..H.num <- as.numeric(mdf.18s$Time..H.)
```
### Figure 2: Alpha over time
```{r alpha-time, fig.height=8, fig.width=6, results="hide"}
alpha.16s.alt <- ggplot(mdf.16s, aes(Time..H., value))
alpha.16s.alt <- alpha.16s.alt +
geom_smooth(color = viridis(n = 10)[8]) +
geom_jitter(width = 0.1) +
facet_grid(facets = variable~Substrate, scales = "free_y", switch = "y") +
labs(x = "Time (h)"
#, title = "16S OTUs"
) +
theme(legend.position = "none",
strip.background = element_blank(),
axis.title.y = element_blank()
#, plot.margin=unit(c(5,5,-25,5), units = "pt")
)
#alpha.16s.alt
alpha.18s.alt <- ggplot(mdf.18s, aes(Time..H., value))
alpha.18s.alt <- alpha.18s.alt +
geom_smooth(color = magma(n = 10)[9]) +
geom_jitter(width = 0.1) +
facet_grid(facets = variable~Substrate, scales = "free_y", switch = "y") +
labs(x = "Time (h)"
#, title = "18S OTUs"
) +
theme(legend.position = "none",
strip.background = element_blank(),
axis.title.y = element_blank()
#axis.text.y = element_blank()
#, plot.margin=unit(c(5,5,-25,5), units = "pt")
)
#alpha.18s.alt
plot_grid(alpha.16s.alt, alpha.18s.alt,
#labels = c("A", "B"),
labels = c("A: 16S OTUs", "B: 18S OTUs"),
align = "v", ncol = 1, hjust = -0.05)
ggsave('fig2-1col.pdf', path = "./figures/", units = "mm", width = 89, height = 120, scale = 1.7)
```
### Additional analysis of alpha diverisity
This is the same graphs from above, using Shannon and Pielou's indexes.
```{r alpha.additional}
rich.16s.alt <- estimate_richness_mod(rar.16s.cohort, measures = c("Shannon", "Pielou"))
rich.18s.alt <- estimate_richness_mod(rar.18s.cohort, measures = c("Shannon", "Pielou"))
# Rename for graphing
graphnames <- c("Shannon", "Pielou")
names(rich.16s.alt) <- graphnames
names(rich.18s.alt) <- graphnames
# merge richness with metadata
DF.16s.alt <- merge(rich.16s.alt, sample_data(rar.16s.cohort), by = 0)
DF.18s.alt <- merge(rich.18s.alt, sample_data(rar.18s.cohort), by = 0)
DF.16s.alt = melt(DF.16s.alt, measure.vars = graphnames)
DF.18s.alt = melt(DF.18s.alt, measure.vars = graphnames)
#head(mdf.16s)
DF.16s.alt$Time..H.num <- as.numeric(DF.16s.alt$Time..H.)
DF.18s.alt$Time..H.num <- as.numeric(DF.18s.alt$Time..H.)
ggplot(DF.16s.alt, aes(Time..H., value)) +
geom_smooth(color = viridis(n = 10)[8]) +
geom_jitter(width = 0.1) +
facet_grid(facets = variable~Substrate, scales = "free_y", switch = "y") +
labs(x = "Time (h)", title = "16S OTUs") +
theme(legend.position = "none",
strip.background = element_blank(),
axis.title.y = element_blank())
ggplot(DF.18s.alt, aes(Time..H., value)) +
geom_smooth(color = magma(n = 10)[9]) +
geom_jitter(width = 0.1) +
facet_grid(facets = variable~Substrate, scales = "free_y", switch = "y") +
labs(x = "Time (h)", title = "18S OTUs") +
theme(legend.position = "none",
strip.background = element_blank(),
axis.title.y = element_blank())
```
#### Alpha over time stat test
Because `n` within each group is small, let's test for equal variance.
Then, use a classic `anova()` test on each combination of Substrate and alpha.
<style>
table, .table {
width: auto;
}
</style>
```{r alpha-time-test}
# For testing
df <- filter(mdf.16s, Substrate == "Glucose", variable == "Evenness")
#table(df$timepoint)
runLevene <- function(df){
t <- leveneTest(value ~ timepoint, data = df) # hardcoded to my data
t
return(t$`Pr(>F)`[1])
}
#by(mdf.16s, INDICES = list(mdf.16s$Substrate, mdf.16s$variable), runLevene)
#by(mdf.18s, INDICES = list(mdf.18s$Substrate, mdf.18s$variable), runLevene)
# Smallest number if for 18S, Glucose:Evenness with p = 0.126, so we are good to go!
runANOVA <- function(df){
res <- lm(value ~ timepoint, data = df) # hardcoded to my data
a <- anova(res)
a
a$`Pr(>F)`[1]
#summary(res)
#TukeyHSD(aov(res), "timepoint") # we don't need to preform a post-hoc test
return(a$`Pr(>F)`[1])
}
# Outputs
kable(
tibble(
Substrate = c("DIC", "Acetate", "Glucose",
"DIC", "Acetate", "Glucose"),
variable = c("Richness", "Richness", "Richness",
"Evenness", "Evenness", "Evenness"),
`ANOVA p-value` = c(
by(mdf.16s, INDICES = list(mdf.16s$Substrate, mdf.16s$variable), runANOVA)
)
)