-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstats_and_plots.r
executable file
·3664 lines (3033 loc) · 156 KB
/
stats_and_plots.r
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
#################################################################
#################################################################
#### ####
#### Script to perform statistical tests and plot figures ####
#### ####
#################################################################
#################################################################
#Written in R v4.0.4
library(ape) #5.6-1
library(ART) #1.0
library(cowplot) #1.1.1
library(deeptime) #0.0.6.0
library(dendextend) #1.15.2
library(plyr) #1.8.6 must be loaded before dplyr to avoid clashes
library(dplyr) #1.0.6
library(eulerr) #6.1.0
library(ggplot2) #3.3.3
library(ggalluvial) #0.12.3
library(ggforce) #0.3.2.9000
library(ggnewscale) #0.4.6
library(ggplotify) #0.0.7
library(ggpubr) #0.4.0
library(ggrepel) #0.9.1
library(ggthemes) #4.2.4
library(ggtree) #2.4.2
library(grid) #4.0.4
library(jsonlite) #1.7.2
library(matrixStats) #0.61.0
library(MCMCtreeR) #1.1
library(metR) #0.9.2
library(multcompView) #0.1-8
library(nlme) #3.1-152
library(pBrackets) #1.0.1
library(phangorn) #2.7.0
library(phytools) #0.7-80
library(reshape2) #1.4.4
library(rstatix) #0.7.0
library(scales) #1.1.1
library(seqinr) #4.2-8
library(stringi) #1.6.2
library(stringr) #1.4.0
library(tidyr) #1.1.3
library(vegan) #2.5-7
#Colour palette
show_col(colorblind_pal()(8))
#Read in orthogroup data
load("CSEP_CAZyme_prediction/orthogroup-matrices-2022-02-10.RData")
#Read in sample metadata
metadata <- read.csv("metadata.csv")
#Make dataframe of lifestyle colours
col.df <- data.frame(lifestyle=c("endophyte", "animal pathogen", "human pathogen","animal associate",
"insect mutualist", "plant associate", "plant pathogen", "saprotroph",
"mycoparasite"),
colour=c("#009E73", "#FFE983", "#000000", "#F1BCF4", "#56B4E9",
"#9AE324", "dimgrey", "#0072B2", "#D55E00"))
############################ FIGURE 1 ####################################
##################### TOPOLOGY COMPARISON ##############################
#Read in trees
astral <- read.tree("phylogenomics/species_tree/astral/fus_proteins_62T_astral.tre")
astral$edge.length <- rep(1, length(astral$edge.length))
raxmlng <- read.tree("phylogenomics/species_tree/raxml-ng/fus_proteins_62T.raxml.support")
iqtree <- read.tree("phylogenomics/species_tree/iqtree/fus_proteins_62T_iqtree.contree")
astral.pro <- read.tree("phylogenomics/species_tree/astral/fus_proteins_62T_astralpro_multicopy.tre")
astral.pro$tip.label <- gsub("-", "_", astral.pro$tip.label)
astral.pro$tip.label[which(astral.pro$tip.label == "Ilysp1_GeneCatalog_proteins")] <- "Ilysp1_GeneCatalog_proteins_20121116"
astral.pro$tip.label <- metadata$file2[match(astral.pro$tip.label, metadata$tip)]
astral.pro$edge.length <- rep(1, length(astral.pro$edge.length))
stag <- read.tree("orthology_inference/OrthoFinder/Results_Oct22/Species_Tree/SpeciesTree_rooted.txt")
#Make vector with outgroup
outgroup <- "Ilyonectria sp."
#Create groupings for whether taxa are Fusarium sensu stricto or allied genera
allied.group <- list(allied=metadata$name[-union(setdiff(grep("Fusarium", metadata$name),
grep("'", metadata$name)), which(metadata$ingroup == 0))],
fusarium=metadata$name[union(setdiff(grep("Fusarium", metadata$name),
grep("'", metadata$name)), which(metadata$ingroup == 0))])
#For each species-tree method...
for (i in c("iqtree", "raxmlng", "astral", "astral.pro", "stag")) {
#Get the tree
tree <- get(i)
tree$tip.label <- metadata$name[match(tree$tip.label, metadata$file2)]
#Root tree
tree <- root(tree, outgroup, resolve.root=TRUE, edgelabel=TRUE)
#Ultrametrise
chrono <- suppressWarnings(chronos(tree))
#Convert to dendrogram for tanglegrams
dend <- as.dendrogram(chrono)
labels(dend) <- metadata$tiplab2[match(labels(dend), metadata$name)]
assign(paste0(i, ".dend"), dend)
#Plot tree
gg <- ggtree(groupOTU(tree, allied.group), aes(colour=group), branch.length="none") %<+% metadata
#Capture data structure
gg.tree.data <- gg[["data"]] %>%
arrange(y)
#Make dataframe of species complex nodes
sc.df <- data.frame(sc=unique(metadata$speciescomplex.abb),
node=NA)
#Get nodes for each species complex
for (j in 1:length(sc.df$sc)) {
sc.df$node[j] <- MRCA(tree, metadata$name[metadata$speciescomplex.abb == sc.df$sc[j]])
}
#Collapse and scale nodes for summary tree
gg.summary <- gg
for (k in 1:length(sc.df$sc)) {
if (table(gg.tree.data$speciescomplex.abb)[
which(names(table(gg.tree.data$speciescomplex.abb)) == sc.df$sc[k])] > 1) {
gg.summary <- scaleClade(gg.summary,
node=sc.df$node[k],
scale=0.4)
}
}
for (k in 1:length(sc.df$sc)) {
if (table(gg.tree.data$speciescomplex.abb)[
which(names(table(gg.tree.data$speciescomplex.abb)) == sc.df$sc[k])] > 1) {
gg.summary <- ggtree::collapse(gg.summary,
node=sc.df$node[k],
mode="max",
clade_name=sc.df$sc[k],
colour="black",
fill="white")
}
}
#Plot summary tree
gg.summary <- gg.summary +
xlim(0, 25) +
geom_cladelab(data=sc.df,
mapping=aes(node=node,
label=sc),
barsize=0,
fontsize=1.5,
align=TRUE,
fontface="bold") +
coord_cartesian(clip="off") +
scale_colour_manual(values=c("red", "black")) +
theme(legend.position="none")
assign(paste0(i, ".tree"), tree)
assign(paste0("gg.", i), gg)
assign(paste0("gg.summary.", i), gg.summary)
assign(paste0("gg.tree.data.", i), gg.tree.data)
}
#Calculate topological distances (RF) between all trees
tree.comp.mat <- signif(as.matrix(RF.dist(c(raxmlng.tree, iqtree.tree, astral.tree, astral.pro.tree, stag.tree),
normalize=TRUE)), 1)
rownames(tree.comp.mat) <- c("RAxML-NG", "IQTREE", "ASTRAL-III", "ASTRAL-Pro", "STAG")
colnames(tree.comp.mat) <- c("RAxML-NG", "IQTREE", "ASTRAL-III", "ASTRAL-Pro", "STAG")
#Convert to dataframe for plotting
tree.comp.df <- melt(tree.comp.mat)
tree.comp.df <- tree.comp.df[!duplicated(data.frame(t(apply(tree.comp.df, 1, sort)))),]
tree.comp.df <- tree.comp.df[tree.comp.df$value != 0,]
#At worst, number of bipartitions which trees differed in
print(paste0(max(tree.comp.df$value) * length(bitsplits(unroot(raxmlng.tree))[3]$freq), "/",
length(bitsplits(unroot(raxmlng.tree))[3]$freq)))
#Make dataframe to label plot
tree.comp.labels <- data.frame(method=c("Concatenated", "Coalescent", "Single-copy", "Multi-copy"),
vert.x=c(0.3, 0.3, 0.1, 0.1),
vert.xend=c(0.3, 0.3, 0.1, 0.1),
vert.y=c(0.5, 1.5, 0.5, 2.5),
vert.yend=c(1.5, 4.5, 2.5, 4.5),
hor.x=c(0.5, 2.5, 0.5, 3.5),
hor.xend=c(2.5, 4.5, 3.5, 4.5),
hor.y=c(4.7, 4.7, 4.9, 4.9),
hor.yend=c(4.7, 4.7, 4.9, 4.9))
#Plot grid
gg.tree.comp <- ggplot(tree.comp.df, aes(Var2, Var1)) +
geom_tile(aes(fill=value), colour="dimgrey", size=1, alpha=0.5, show.legend=FALSE) +
geom_text(aes(label=value), size=1.5, show.legend=FALSE) +
geom_segment(data=tree.comp.labels,
aes(x=vert.x, xend=vert.xend, y=vert.y, yend=vert.yend, colour=method),
size=1.5,
inherit.aes=FALSE) +
geom_segment(data=tree.comp.labels,
aes(x=hor.x, xend=hor.xend, y=hor.y, yend=hor.yend, colour=method),
size=1.5,
inherit.aes=FALSE) +
scale_x_discrete(position="top") +
scale_fill_gradient(low="white", high="dimgrey") +
scale_colour_manual(values=c("#E69F00", "#009E73", "#56B4E9", "#F0E442")) +
theme_minimal() +
theme(legend.position=c(0.8, 0.25),
legend.title=element_blank(),
legend.key.height=unit(0.2, "cm"),
legend.text=element_text(size=4.5, margin=margin(0, 0, 0, -5)),
axis.text.x.top=element_text(size=3.5, face="bold", margin=margin(0, 0, 5, 0)),
axis.text.y=element_text(face="bold", angle=90, hjust=0.5, vjust=0,
size=3.5, margin=margin(0, 5, 0, 0)),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
panel.grid=element_blank()) +
coord_fixed(clip="off")
#Write topology comparison to file (Figure 1)
#tiff(file=paste0("Fig1-", Sys.Date(), ".tiff"),
# height=2, width=6.75, unit="in", res=600, compression="lzw")
plot_grid(gg.tree.comp,
plot_grid(gg.summary.raxmlng +
geom_segment(aes(x=-Inf, xend=Inf,
y=7,
yend=7),
colour="#009E73",
size=1.5) +
geom_segment(aes(x=-Inf, xend=Inf,
y=6,
yend=6),
colour="#F0E442",
size=1.5) +
annotate("text", label="RAxML-NG", size=2, angle=90, fontface="bold", x=0.5, y=32),
gg.summary.iqtree +
geom_segment(aes(x=-Inf, xend=Inf,
y=7,
yend=7),
colour="#009E73",
size=1.5) +
geom_segment(aes(x=-Inf, xend=Inf,
y=6,
yend=6),
colour="#F0E442",
size=1.5) +
annotate("text", label="IQ-TREE", size=2, angle=90, fontface="bold", x=0.5, y=32),
gg.summary.astral +
geom_segment(aes(x=-Inf, xend=Inf,
y=7,
yend=7),
colour="#E69F00",
size=1.5) +
geom_segment(aes(x=-Inf, xend=Inf,
y=6,
yend=6),
colour="#F0E442",
size=1.5) +
annotate("text", label="ASTRAL-III", size=2, angle=90, fontface="bold", x=0.5, y=32),
gg.summary.astral.pro +
geom_segment(aes(x=-Inf, xend=Inf,
y=7,
yend=7),
colour="#E69F00",
size=1.5) +
geom_segment(aes(x=-Inf, xend=Inf,
y=6,
yend=6),
colour="#56B4E9",
size=1.5) +
annotate("text", label="ASTRAL-Pro", size=2, angle=90, fontface="bold", x=0.5, y=32),
gg.summary.stag +
geom_segment(aes(x=-Inf, xend=Inf,
y=7,
yend=7),
colour="#E69F00",
size=1.5) +
geom_segment(aes(x=-Inf, xend=Inf,
y=6,
yend=6),
colour="#56B4E9",
size=1.5) +
annotate("text", label="STAG", size=2, angle=90, fontface="bold", x=0.5, y=32),
nrow=1),
nrow=1, labels="AUTO", label_size=10, rel_widths=c(1, 2.8))
#dev.off()
## Comparison of trimming tools
raxmlng.bmge <- read.tree("phylogenomics/species_tree/raxml-ng/fus_proteins_bmge_62T.raxml.support")
iqtree.bmge <- read.tree("phylogenomics/species_tree/iqtree/fus_proteins_bmge_62T_iqtree.contree")
astral.bmge <- read.tree("phylogenomics/species_tree/astral/fus_proteins_bmge_62T_astral.tre")
astral.bmge$edge.length <- rep(1, length(astral.bmge$edge.length))
for (i in c("iqtree", "raxmlng", "astral")) {
#Get the tree
tree <- get(paste0(i, ".bmge"))
#Edit tip names
tree$tip.label <- metadata$name[match(tree$tip.label, metadata$tip)]
#Root tree
tree <- root(tree, outgroup, resolve.root=TRUE, edgelabel=TRUE)
#Ultrametrise
chrono <- suppressWarnings(chronos(tree))
#Convert to dendrogram for tanglegram
dend <- as.dendrogram(chrono)
labels(dend) <- metadata$tiplab2[match(labels(dend), metadata$name)]
#Untangle dendrograms from both trimming tools
dend.comp <- untangle_labels(get(paste0(i, ".dend")), dend, method="step2side")
#Plot first tree
tr1 <- ggtree(as.phylo(dend.comp[[1]]), branch.length = "none",
aes(lty=node %in%
matchNodes(
as.phylo(dend.comp[[1]]),
as.phylo(dend.comp[[2]]))[
which(is.na(matchNodes(
as.phylo(dend.comp[[1]]),
as.phylo(dend.comp[[2]]))[,2])),1])) +
xlim(0, 35) +
geom_tiplab(size=2) +
scale_y_continuous(expand=c(0, 2)) +
theme_void() +
theme(legend.position="none")
#Plot second tree
tr2 <- ggtree(as.phylo(dend.comp[[2]]), branch.length = "none",
aes(lty=node %in%
matchNodes(
as.phylo(dend.comp[[2]]),
as.phylo(dend.comp[[1]]))[
which(is.na(matchNodes(
as.phylo(dend.comp[[2]]),
as.phylo(dend.comp[[1]]))[,2])),1])) +
geom_tiplab(size=2, hjust=1) +
scale_x_reverse() +
xlim(35, 0) +
scale_y_continuous(expand=c(0, 2)) +
theme_void() +
theme(legend.position="none")
#Plot dataframe for tanglegram lines
lines.df <- data.frame(y1=tr1$data$y[tr1$data$isTip == TRUE],
y2=tr2$data$y[match(tr1$data$label[tr1$data$isTip == TRUE],
tr2$data$label[tr2$data$isTip == TRUE])],
col="same")
lines.df$col[which(lines.df$y1 != lines.df$y2)] <- "diff"
if ("diff" %in% lines.df$col) {
#Plot lines
gg.lines <- ggplot() +
geom_segment(data=lines.df,
aes(x=0,
y=y1,
xend=1,
yend=y2,
col=col)) +
scale_colour_manual(values=c("black", "grey")) +
scale_y_continuous(expand=c(0, 2)) +
theme_void() +
theme(legend.position="none")
} else {
gg.lines <- ggplot() +
geom_segment(data=lines.df,
aes(x=0,
y=y1,
xend=1,
yend=y2),
col="grey") +
scale_y_continuous(expand=c(0, 2)) +
theme_void() +
theme(legend.position="none")
}
#Combine into tanglegram
tanglegram <- plot_grid(tr1, gg.lines, tr2, ncol=3, rel_widths=c(2, 0.3, 2), align="h", axis="bt")
assign(paste0(i, ".trim.tanglegram"), tanglegram)
}
#Write tanglegram to file (Supplementary Figure 2)
#tiff(file=paste0("SupplementaryFig2-", Sys.Date(), ".tiff"),
# height=15, width=6.75, unit="in", res=600, compression="lzw")
plot_grid(labels="AUTO", label_size=10, ncol=1, rel_heights=c(1,1,1.1),
raxmlng.trim.tanglegram, iqtree.trim.tanglegram,
ggdraw(add_sub(astral.trim.tanglegram, "TrimAl\t\t\t\t\t\t\t\t\t\t\t\t\tBMGE", size=10)))
#dev.off()
####################################
#Check distributions of branch lengths
branch.lengths.df <- data.frame(raxmlng=raxmlng.tree$edge.length, iqtree=iqtree.tree$edge.length, stag=stag.tree$edge.length)
branch.lengths.df2 <- melt(branch.lengths.df)
ggplot(branch.lengths.df2, aes(x=value)) +
facet_wrap(~ variable,
labeller=labeller(variable=c(raxmlng="RAxML-NG", iqtree="IQ-TREE", stag="STAG"))) +
geom_density(alpha=0.5, fill="grey") +
labs(x="Branch length (#substitutions/site)", y="Density") +
theme_minimal() +
theme(legend.position="none",
axis.text=element_blank())
###############################
#Proportion of supported branches
#RAxML-NG Felsenstein's bootstrap >= 70
suppressWarnings(round(length(which(as.numeric(raxmlng$node.label) >= 70)) /
length(na.omit(as.numeric(raxmlng$node.label))) * 100))
#IQ-TREE ultrafast bootstrap >= 95
suppressWarnings(round(length(which(as.numeric(iqtree$node.label) >= 95)) /
length(na.omit(as.numeric(iqtree$node.label))) * 100))
#ASTRAL-III LPP >= 0.95
suppressWarnings(round(length(which(as.numeric(astral$node.label) >= 0.95)) /
length(na.omit(as.numeric(astral$node.label))) * 100))
#ASTRAL-Pro LPP >=0.95
suppressWarnings(round(length(which(as.numeric(astral.pro$node.label) >= 0.95)) /
length(na.omit(as.numeric(astral.pro$node.label))) * 100))
#STAG proportion of trees with same branch >=0.30
suppressWarnings(round(length(which(as.numeric(stag$node.label) >= 0.30)) /
length(na.omit(as.numeric(stag$node.label))) * 100))
############################ FIGURE 2 ####################################
##################### PHYLOGENY AND LIFESTYLE ##############################
## MCMCTREE CONVERGENCE PLOTS ##
#For each relax clock model...
for (i in c("independent", "correlated")) {
#Read in the generation data
mcmc1.gens <- read.csv(paste0("divergence_time_estimation/mcmctree/run1_", i, "/mcmc_run1_", i, ".txt"), sep="\t")
mcmc2.gens <- read.csv(paste0("divergence_time_estimation/mcmctree/run2_", i, "/mcmc_run2_", i, ".txt"), sep="\t")
#Calculate the effective sample size
ESS <- mean(apply(mcmc1.gens[,-1], 2, effectiveSize))
#Make dataframe of posterior means for both chains
mcmc.df <- data.frame(run1=colMeans(mcmc1.gens[2:62]),
run2=colMeans(mcmc2.gens[2:62]))
#Plot chain convergence
gg.mcmc <- ggplot(mcmc.df, aes(x=run1, y=run2)) +
geom_abline(colour="dimgrey") +
geom_point() +
labs(x="Posterior mean chain 1 (100MY)",
y="Posterior mean chain 2 (100MY)",
subtitle=paste0("ESS=", round(ESS))) +
coord_fixed() +
theme(axis.title=element_text(size=6),
axis.text=element_text(size=5),
plot.subtitle=element_text(size=8))
assign(paste0("gg.mcmc.", i), gg.mcmc)
#Read in and format MCMCTRee output
mcmc1.out <- read.csv(paste0("divergence_time_estimation/mcmctree/run1_", i, "/mcmctree_step2_out.txt"),
sep="\t", skip=616, nrows=61, header=FALSE)
mcmc1.out <- as.data.frame(do.call(rbind, strsplit(mcmc1.out$V1, "\\s+")))
mcmc1.out <- mcmc1.out[1:7]
colnames(mcmc1.out) <- c("node", "posterior_mean", "95_equal_tail_CI_lower", "95_equal_tail_CI_upper",
"95_HPD_CI_lower", "95_HPD_CI_upper", "HPD_CI_width")
mcmc1.out[] <- lapply(mcmc1.out, function(x) gsub("\\(", "", x))
mcmc1.out[] <- lapply(mcmc1.out, function(x) gsub("\\)", "", x))
mcmc1.out[] <- lapply(mcmc1.out, function(x) gsub(",", "", x))
mcmc1.out[2:7] <- data.frame(apply(mcmc1.out[2:7], 2, function(x) as.numeric(as.character(x))))
#Calculate confidence interval width
mcmc1.out$HPD_CI_width <- mcmc1.out$`95_HPD_CI_upper` - mcmc1.out$`95_HPD_CI_lower`
#Plot infinite-sites plot
gg.infinitesite <- ggplot(mcmc1.out, aes(x=posterior_mean, y=HPD_CI_width)) +
geom_smooth(method="lm", se=FALSE, colour="dimgrey") +
geom_point() +
labs(x="Posterior mean chain 1 (100MY)",
y="Confidence interval width (100MY)") +
theme(axis.title=element_text(size=6),
axis.text=element_text(size=5))
assign(paste0("gg.infinitesite.", i), gg.infinitesite)
}
#Write to file (Supplementary Figure 12)
#tiff(file=paste0("SupplementaryFig12-", Sys.Date(), ".tiff"),
# height=4, width=6.75, units="in", res=600, compression="lzw")
plot_grid(plot_grid(gg.mcmc.correlated, gg.infinitesite.correlated, align="h", axis="tb"),
plot_grid(gg.mcmc.independent, gg.infinitesite.independent, align="h", axis="tb"), nrow=2,
labels="AUTO", label_size=10)
#dev.off()
## DATED PHYLOGENY ##
#Plot species tree
gg.speciestree <- ggtree(raxmlng.tree, branch.length="none") %<+% metadata
#Capture species tree data structure
gg.tree.data.speciestree <- gg.speciestree[["data"]] %>%
arrange(y)
#For analyses from both relaxed molecular clock methods...
for (clock in c("independent", "correlated")) {
#Read in MCMCTree tree
dated.tree <- readMCMCtree(paste0("divergence_time_estimation/mcmctree/run1_", clock, "/FigTree.tre"),
forceUltrametric=TRUE)
#Convert branch length unit to 1MY
dated.tree$apePhy$edge.length <- dated.tree$apePhy$edge.length * 100
#Replace tip labels with names
dated.tree$apePhy$tip.label <- metadata$name[match(dated.tree$apePhy$tip.label, metadata$short.tip)]
#Add ML support values from to correct nodes
nodes <- matchNodes(raxmlng.tree, dated.tree$apePhy)
dated.tree$apePhy$node.label <- gg.tree.data.speciestree$label[
match(nodes[,1], gg.tree.data.speciestree$node)][order(nodes[,2])]
assign(paste0("dated.tree.", clock), dated.tree)
#Plot tree
gg.datedtree <- ggtree(dated.tree$apePhy, linetype=NA) %<+% metadata
#Create vector with the order of the tree tips for plotting
gg.tree.data.dated <- gg.datedtree[["data"]] %>%
arrange(y)
tip.order.datedtree <- rev(gg.tree.data.dated$label[gg.tree.data.dated$isTip == "TRUE"])
#Create vector of fontface for new genomes in this study
label.face.datedtree <- rev(metadata$new[match(tip.order.datedtree, metadata$name)])
for (i in 1:length(label.face.datedtree)){
if (label.face.datedtree[i] == "Y") {
label.face.datedtree[i] <- "bold.italic"
} else {
label.face.datedtree[i] <- "italic"
}
}
tiplabel.face.datedtree <- rep("italic", length(dated.tree$apePhy$tip.label))
tiplabel.face.datedtree[which(metadata$new[
match(dated.tree$apePhy$tip.label, metadata$name)] == "Y")] <- "bold.italic"
#Make dataframe for plotting divergence time confidence intervals
confidence.intervals <- as.data.frame(dated.tree$nodeAges)
confidence.intervals <- confidence.intervals * 100
confidence.intervals$ymin <- gg.tree.data.dated$y[match(rownames(confidence.intervals),
gg.tree.data.dated$node)] -0.2
confidence.intervals$ymax <- gg.tree.data.dated$y[match(rownames(confidence.intervals),
gg.tree.data.dated$node)] +0.2
#Add time scale to tree plot
gg.datedtree <- gg.datedtree +
coord_geo(clip="off",
xlim=c(max(confidence.intervals$`95%_upper`) * -1, 70),
ylim=c(0, Ntip(dated.tree$apePhy)),
dat=list("epochs", "periods"),
pos=list("bottom", "bottom"),
size=list(1,1.5),
height=list(unit(0.25, "line"), unit(0.5, "line")),
abbrv=list(TRUE, FALSE),
center_end_labels=TRUE,
lwd=0, alpha=0.5, neg=TRUE, expand=FALSE) +
scale_x_continuous(breaks=rev(seq(0, round(max(confidence.intervals$`95%_upper`)), 10)) * -1,
labels=rev(seq(0, round(max(confidence.intervals$`95%_upper`)), 10)),
expand=c(0, 0),
name="Million years") +
theme(axis.text.x.bottom=element_text(size=5),
axis.title.x.bottom=element_text(size=5))
#Reverse the x axis
gg.datedtree <- revts(gg.datedtree)
#Make dataframe of species complex nodes
sc.df.dated <- data.frame(sc=unique(metadata$speciescomplex.abb),
node=NA)
#Get nodes for each species complex
for (i in 1:length(sc.df.dated$sc)) {
sc.df.dated$node[i] <- MRCA(dated.tree$apePhy,
metadata$name[metadata$speciescomplex.abb == sc.df.dated$sc[i]])
}
#Make alternated coding for highlights on tree
sc.df.dated <- sc.df.dated[match(na.omit(unique(gg.tree.data.dated$speciescomplex.abb)), sc.df.dated$sc),]
sc.df.dated$box <- rep(c(0,1), length.out=length(sc.df.dated$sc))
#Add final annotations to tree plot
gg.datedtree <- gg.datedtree +
geom_highlight(data=sc.df.dated,
aes(node=node, fill=as.factor(box)), alpha=1, extend=200, show.legend=FALSE) +
geom_cladelab(data=sc.df.dated,
mapping=aes(node=node, label=sc),
offset.text=2, offset=70, align=TRUE, barsize=0.2, fontsize=1.5) +
geom_rect(data=confidence.intervals,
aes(xmin=`95%_lower` * -1,
xmax=`95%_upper` * -1,
ymin=ymin,
ymax=ymax),
alpha=0.1,
size=0.1,
colour="grey",
inherit.aes=FALSE) +
geom_point(data=confidence.intervals,
aes(x=mean * -1,
y=ymin + 0.2),
colour="grey",
size=0.5,
inherit.aes=FALSE) +
scale_fill_manual(values=c("#F5F5F5", "#ECECEC")) +
geom_vline(xintercept=epochs$max_age[which((epochs$max_age) < max(confidence.intervals$`95%_upper`))] * -1,
linetype="dashed", colour="grey", size=0.2) +
geom_tiplab(aes(label=tiplab), fontface=tiplabel.face.datedtree, size=1.5, offset=1) +
geom_tippoint(aes(colour=lifestyle), size=0.7, show.legend=FALSE) +
scale_colour_manual(values=col.df$colour[match(sort(unique(metadata$lifestyle[match(dated.tree$apePhy$tip.label,
metadata$name)])),
col.df$lifestyle)]) +
new_scale_colour() +
geom_tree(size=0.25, aes(colour=node %in% gg.datedtree$data$node[
suppressWarnings(intersect(which(as.numeric(gg.datedtree$data$label) < 70),
which(gg.datedtree$data$isTip == FALSE)))]),
show.legend=FALSE) +
scale_colour_manual(values=c("black", "red"))
#Format confidence intervals for table
confidence.intervals.tab <- data.frame(Node=as.numeric(rownames(confidence.intervals)) - Ntip(dated.tree$apePhy),
Mean.age=round(confidence.intervals$mean, digits=1),
`95.HPD`=paste0(round(confidence.intervals$`95%_lower`, digits=1), ", ",
round(confidence.intervals$`95%_upper`, digits=1)))
confidence.intervals.tab <- split(confidence.intervals.tab,
rep(c("first", "second"),
each=ceiling(length(confidence.intervals.tab$Node)/2)))
#Plot confidence intervals table in two separate columns
for (i in c("first", "second")) {
gg.ci <- ggtexttable(confidence.intervals.tab[[i]],
rows=NULL,
theme=ttheme(base_size=3,
padding=unit(c(1, 1), "mm")),
cols=c("Node", "Mean age", "95% HPD"))
assign(paste0("gg.ci.", i, ".", clock), gg.ci)
}
assign(paste0("gg.datedtree.", clock), gg.datedtree)
assign(paste0("gg.tree.data.dated.", clock), gg.tree.data.dated)
}
#Write dated trees with confidence interval tables to file (Supplementary Figure 3)
#tiff(file=paste0("SupplementaryFig3-", Sys.Date(), ".tiff"),
# height=8, width=6.75, unit="in", res=600, compression="lzw")
plot_grid(plot_grid(gg.datedtree.correlated +
geom_text_repel(data=gg.tree.data.dated.correlated[
gg.tree.data.dated.correlated$node %in% c(64, 66),],
aes(x=x-max(gg.tree.data.dated.correlated$x), y=y,
label=c("Generic concept\nsensu lato",
"Generic concept\nsensu stricto")),
hjust=1,
size=1.1,
segment.size=0.25,
min.segment.length=unit(0, 'lines'),
xlim=c(-Inf, Inf),
nudge_x=-3,
nudge_y=2.5) +
geom_label2(aes(subset=!isTip, label=node - Ntip(dated.tree$apePhy)),
size=1, label.padding=unit(1, "pt")) +
theme(plot.margin=margin(0.8, 1, 0, 0, unit="cm")),
gg.ci.first.correlated, gg.ci.second.correlated,
rel_widths=c(6, 1 ,1), nrow=1, align="h", axis="tb"),
plot_grid(gg.datedtree.independent +
geom_text_repel(data=gg.tree.data.dated.independent[
gg.tree.data.dated.independent$node %in% c(64, 66),],
aes(x=x-max(gg.tree.data.dated.independent$x), y=y,
label=c("Generic concept\nsensu lato",
"Generic concept\nsensu stricto")),
hjust=1,
size=1.1,
segment.size=0.25,
min.segment.length=unit(0, 'lines'),
xlim=c(-Inf, Inf),
nudge_x=-3,
nudge_y=2.5) +
geom_label2(aes(subset=!isTip, label=node - Ntip(dated.tree$apePhy)),
size=1, label.padding=unit(1, "pt")) +
theme(plot.margin=margin(0.8, 1, 0, 0, unit="cm")),
gg.ci.first.independent, gg.ci.second.independent,
rel_widths=c(6, 1 ,1), nrow=1, align="h", axis="tb"),
ncol=1, labels="AUTO", label_size=10, align="v", axis="lr")
#dev.off()
## NUMBER OF GENES/CSEPs BARGRAPH ##
#Filter orthogroup presence-absence matrix for orthogroups with at least one predicted CSEP/CAZyme
CSEP.orthogroups <- orthogroups.count.ingroup1[
match(rownames(CSEP.count.ingroup1)[which(rowSums(CSEP.count.ingroup1) > 0)],
rownames(orthogroups.count.ingroup1)),]
CAZyme.orthogroups <- orthogroups.count.ingroup1[
match(rownames(CAZyme.count.ingroup1)[which(rowSums(CAZyme.count.ingroup1) > 0)],
rownames(orthogroups.count.ingroup1)),]
#Read in phylogenetic PCA from lifestyle test results
for (i in c("CSEPs", "CAZymes", "orthogroups")) {
phy.pca.result <- read.csv(paste0("lifestyle_comparison/", i, "/metadata.csv"))
rownames(phy.pca.result) <- metadata$file2[match(phy.pca.result$genome, metadata$short.tip)]
assign(paste0("phy.pca.result.", i), phy.pca.result)
}
#For each category...
for (i in c("orthogroup", "CSEP", "CAZyme")) {
if (i == "orthogroup") {
tmp.orthogroups <- orthogroups.count.ingroup1
} else {
tmp.orthogroups <- get(paste0(i, ".orthogroups"))
}
#Check for correlation between N50 and number of CSEPs/CAZymes
tmp.df <- data.frame(num=colSums(tmp.orthogroups > 0))
tmp.df$taxon <- rownames(tmp.df)
tmp.df$lifestyle <- metadata$lifestyle[match(tmp.df$taxon, metadata$file2)]
tmp.df$N50 <- metadata$N50[match(tmp.df$taxon, metadata$file2)]
cor <- cor.test(tmp.df$num, tmp.df$N50)
if (cor$p.value >= 0.05) {
print(paste0("No correlation between N50 and number of ", i, "s"))
} else {
print(paste0("Correlation between N50 and number of ", i, "s"))
}
#Add PC1 and PC2
tmp.df <- cbind(tmp.df,
phy.pca.result.orthogroups[match(tmp.df$taxon,
rownames(phy.pca.result.orthogroups)),
c("PC1", "PC2")])
#Test for significant difference in number of CSEPs/CAZymes between lifestyles
#Check for normality of residuals
plot(ggqqplot(residuals(lm(num ~ lifestyle, data=tmp.df))) +
ggtitle(i))
#Check for homogeneity of variances
num.genes.levene <- tmp.df %>% levene_test(num ~ lifestyle)
num.genes.levene <- data.frame(formula=paste0("Number of ", i, "s ~ lifestyle"), num.genes.levene)
assign(paste0("num.genes.levene.", i), num.genes.levene)
#If homogeneity of variance assumption met...
if (num.genes.levene$p >= 0.05) {
print("Homogeneity of variance assumption met, doing ANOVA")
#Do ANOVA including lifestyle and first 2 PCs
num.genes.anova <- tmp.df %>% anova_test(num ~ PC1 + PC2 + lifestyle)
#Format
num.genes.anova[, c(3, 6, 7)] <- NULL
colnames(num.genes.anova) <- c("Effect", "Df", "F", "p")
num.genes.anova$formula <- paste0("Number of ", i, "s ~ PC1 + PC2 + lifestyle")
assign(paste0("num.genes.anova.", i), num.genes.anova)
num.genes.p <- num.genes.anova$p[3]
#If ANOVA is significant...
if (num.genes.p < 0.05) {
print("Number of ", i, "s significant according to ANOVA, doing TukeyHSD")
#Do TukeyHSD pairwise tests
num.genes.pw.df <- tmp.df %>% tukey_hsd(num ~ lifestyle)
num.genes.pw.df[c(1, 4, 9)] <- NULL
num.genes.pw.df$formula <- paste0("Number of ", i, "s ~ lifestyle")
assign(paste0("num.genes.pw.df.", i), num.genes.pw.df)
} else {
print(paste0("ANOVA, number of ", i, "s not significant: p=", signif(num.genes.p, 1)))
}
} else {
print("Homogeneity of variance assumption not met, doing aligned rank tranform ANOVA")
#Do ART
num.genes.anova <- aligned.rank.transform(num ~ PC1 + PC2 + lifestyle, data=tmp.df)
#Format
num.genes.anova$significance$`Sum Sq` <- NULL
colnames(num.genes.anova$significance) <- c("Df", "F", "p")
num.genes.anova$significance$Effect <- rownames(num.genes.anova$significance)
num.genes.anova$significance$formula <- paste0("Number of ", i, "s ~ PC1 + PC2 + lifestyle")
assign(paste0("num.genes.anova.", i), num.genes.anova)
num.genes.p <- num.genes.anova$significance$p[3]
#If ANOVA is significant...
if (num.genes.p < 0.05) {
print("Number of ", i, "s significant according to aligned rank transform ANOVA, doing Games Howell test")
#Do Games Howell pairwise tests
num.genes.pw.df <- tmp.df %>% games_howell_test(num ~ lifestyle)
num.genes.pw.df[c(1, 8)] <- NULL
num.genes.pw.df$formula <- paste0("Number of ", i, "s ~ lifestyle")
assign(paste0("num.genes.pw.df.", i), num.genes.pw.df)
} else {
print(paste0("Aligned rank transform ANOVA, number of ", i,
"s not significant: p=", signif(num.genes.p, 1)))
}
}
}
#Make dataframe categorising genes into core, accessory or specific
genes.df <- data.frame(taxon=rep(colnames(orthogroups.count.ingroup1), each=3),
category=rep(c("specific", "accessory", "core"),
length(colnames(orthogroups.count.ingroup1))),
orthogroups=NA,
CSEPs=NA,
CAZymes=NA)
#For each taxon...
for (i in unique(genes.df$taxon)) {
#For each category...
for (j in unique(genes.df$category)) {
#Get number of orthogroups
genes.df$orthogroups[intersect(which(genes.df$taxon == i), which(genes.df$category == j))] <-
table(orthogroups.stats.ingroup1$category[
match(rownames(orthogroups.count.ingroup1[orthogroups.count.ingroup1[, i] > 0,]),
orthogroups.stats.ingroup1$orthogroup)])[j]
#Get number of CSEPs
genes.df$CSEPs[intersect(which(genes.df$taxon == i), which(genes.df$category == j))] <-
table(orthogroups.stats.ingroup1$category[
match(rownames(CSEP.orthogroups[CSEP.orthogroups[, i] > 0,]),
orthogroups.stats.ingroup1$orthogroup)])[j]
#Get number of CAZymes
genes.df$CAZymes[intersect(which(genes.df$taxon == i), which(genes.df$category == j))] <-
table(orthogroups.stats.ingroup1$category[
match(rownames(CAZyme.orthogroups[CAZyme.orthogroups[, i] > 0,]),
orthogroups.stats.ingroup1$orthogroup)])[j]
}
}
#Add taxon name
genes.df$name <- metadata$name[match(genes.df$taxon, metadata$file2)]
#Order categories
genes.df$category <- factor(genes.df$category, levels=c("specific", "accessory", "core"))
#Order taxa by tips in the tree
genes.df$name <- factor(genes.df$name, levels=rev(tip.order.datedtree))
#Melt for plotting
genes.df <- melt(genes.df)
#Add column for order of taxa in tree
genes.df$y <- as.numeric(factor(genes.df$name))
#Make function for dynamic axis labels
addUnits <- function(n) {
labels <- ifelse(n < 1000, n,
ifelse(n < 1e6, paste0(round(n/1e3), 'k')
)
)
return(labels)
}
#Plot bargraphs of number of genes
gg.gene.numbers <- ggplot(genes.df, aes(y=name, x=value, fill=category)) +
facet_wrap(. ~ variable, scales="free",
labeller=labeller(variable=c(CAZymes="CAZymes", CSEPs="CSEPs", orthogroups="All genes"))) +
geom_bar(stat="identity", size=0.5, width=0.6) +
scale_y_discrete(limits=rev(tip.order.datedtree),
expand=expansion(0, 0)) +
coord_cartesian(clip="off",
ylim=c(0, 62)) +
guides(fill=guide_legend(nrow=1)) +
scale_x_continuous(expand=c(0, 0),
position="top",
labels=addUnits) +
scale_fill_manual(values=c("lightgrey", "darkgrey", "dimgrey"),
breaks=c("core", "accessory", "specific"),
labels=c("Core", "Accessory", "Specific")) +
theme_minimal() +
theme(strip.placement="outside",
strip.text=element_text(size=6, margin=margin(0, 0, 1, 0)),
axis.title=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
axis.text.x.top=element_text(size=3),
panel.grid.major.x=element_line(colour="white"),
panel.grid.minor.x=element_line(colour="white"),
panel.grid.major.y=element_blank(),
legend.position=c(0.5, 0),
legend.text=element_text(size=6, margin=margin(0, 4, 0, 0)),
legend.key.size=unit(0.2, "cm"),
legend.spacing.x=unit(0.1, "cm"),
legend.title=element_blank())
## NAMED CSEPS ABUNDANCE MATRIX ##
#Proportion of CSEPs that could be functionally annotated
length(which(!is.na(orthogroups.stats.ingroup0$CSEP_name))) /
length(which(!is.na(orthogroups.stats.ingroup0$CSEP)))
#Read in PHI-base data
phibase.df <- read.csv("CSEP_CAZyme_prediction/blastp/phi-base_current.csv")
csep.name.list <- list()
#For each taxon...
for (i in unique(genes.df$taxon)) {
#Get numbers of named CSEPs
csep.name.list[[i]] <-
as.list(table(sub(",.*", "", orthogroups.stats.ingroup1$PHI.base_entry[
match(rownames(orthogroups.count.ingroup1[orthogroups.count.ingroup1[, i] > 0,]),
orthogroups.stats.ingroup1$orthogroup)])))
#Format CSEP names
names(csep.name.list[[i]]) <- sub("_.*", "", names(csep.name.list[[i]]))
}
#Melt into dataframe
csep.name.df <- melt(data.frame(taxon=names(csep.name.list),
data.table::rbindlist(csep.name.list, fill=TRUE, use.names=TRUE)))
csep.name.df$CSEP_name <- phibase.df$Gene[match(gsub("\\.", ":", csep.name.df$variable),
phibase.df$PHI_MolConn_ID)]
#Add mutant phenotypes
csep.name.df$group <- phibase.df$Mutant.Phenotype[match(gsub("\\.", ":", csep.name.df$variable),
phibase.df$PHI_MolConn_ID)]
#Format group labels
csep.name.df$group <- str_to_sentence(csep.name.df$group)
csep.name.df$group <- sub("Effector \\(plant avirulence determinant\\)", "Effector", csep.name.df$group)
csep.name.df$group <- sub("Increased virulence \\(hypervirulence\\)", "Hyp", csep.name.df$group)
csep.name.df$group <- sub("Loss of pathogenicity", "Loss\npath", csep.name.df$group)
csep.name.df$group <- sub("Lethal", "L", csep.name.df$group)
#Add taxon name
csep.name.df$name <- metadata$name[match(csep.name.df$taxon, metadata$file2)]
csep.name.df$tiplab <- metadata$tiplab2[match(csep.name.df$taxon, metadata$file2)]
#Order taxa by tips in the tree
csep.name.df$name <- factor(csep.name.df$name, levels=rev(tip.order.datedtree))
#Add whether CSEP was also predicted to be a CAZyme
csep.name.df$CAZyme <- 1
for (i in unique(csep.name.df$variable)) {
matches <- unique(orthogroups.stats.ingroup1$CAZyme_family[grep(gsub("\\.", ":", i),
orthogroups.stats.ingroup1$PHI.base_entry)])
if (TRUE %in% !is.na(matches)) {
csep.name.df$CAZyme[csep.name.df$variable == i] <- 2
}
}
csep.name.df$CSEP_name <- sub(" \\(.*", "", csep.name.df$CSEP_name)
#Correct or summarise gene names for plotting
csep.name.df$CSEP_name[grep("O-methylsterigmatocystin oxidoreductase", csep.name.df$CSEP_name)] <- "ordA"
csep.name.df$CSEP_name[grep("endo-1,4-beta-xylanase", csep.name.df$CSEP_name)] <-
gsub(".*\\[| family]", "", csep.name.df$CSEP_name[grep("endo-1,4-beta-xylanase", csep.name.df$CSEP_name)])
csep.name.df$CSEP_name <- sub("Six", "SIX", csep.name.df$CSEP_name)
#Order in plot
csep.name.df$CSEP_name <-
factor(csep.name.df$CSEP_name,