-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFigures_v3.Rmd
3184 lines (2680 loc) · 142 KB
/
Figures_v3.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: "Negative global-scale association between genetic diversity and speciation rates in mammals - results_v2"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
highlight: tango
code_folding: hide
depth: 4
number_sections: no
theme: sandstone
toc: yes
toc_float:
collapsed: true
smooth_scroll: true
mainfont: "Arial"
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
folder_path <- '/Users/acas/Dropbox/Post-docs/Morlon_Lab/manuscript_projects_info/mammals_genDiv_SpRate/manuscript_scripts_data/thirdSubmission/'
fig_path <- paste0(folder_path,'figures_tables/')
library(knitr)
library(flextable)
library(officer)
library(tidyverse)
library(caper)
library(ape)
library(phytools)
library(tidybayes)
library(Rmisc)
library(hues)
library(RColorBrewer)
library(fields)
library(plotrix)
library(ggpubr)
library(gridExtra)
library(scales)
library(ggtree)
library(gt)
library(cowplot)
library(patchwork)
library(nlme)
library(ggh4x)
library(geosphere)
library(showtext)
library(scico)
source(paste0(folder_path,'5.speciation_rate/scripts/match_edges.R')) #to plot data in phylogeny
filter = dplyr::filter
count = dplyr::count
mutate = dplyr::mutate
select = dplyr::select
rename = dplyr::rename
recode = dplyr::recode
opts_chunk$set(tidy=TRUE,
echo = TRUE,
cache = FALSE,
message=FALSE,
warning=FALSE)
opts_knit$set(progress = TRUE, verbose = TRUE)
font_add("Arial", regular = "arial.ttf")
showtext_auto()
fon <- 'Arial'
theme_set(theme(text = element_text(family=fon)))
```
```{r}
gen.div <- read.delim(paste0(folder_path, '4.genetic_diversity/outputs/GenDiv_SynNonSyn_resampled4ind.txt')) %>%
filter(EstPiSyn > 0, outPiSyn %in% 'in', outThetaSyn %in% 'in')
##load phylogenies and speciation rates from 100 posterior trees + MCC tree
TreeRatesSet <- readRDS(paste0(folder_path,'5.speciation_rate/outputs/MCCposterior100_treeMAPS.rds'))
treeMCC <- TreeRatesSet[["treeMCC"]][["tree"]]
ratesMCC <- TreeRatesSet[["treeMCC"]][["rates"]][!is.na(names(TreeRatesSet[["treeMCC"]][["rates"]]))][-c(1:4)]
parClaDS <- tibble(rates = purrr::map(TreeRatesSet,'rates')) %>%
hoist(rates,
sigma = "sigma",
alpha = "alpha",
epsilon = "epsilon",
lambda_0 = "lambda_0") %>%
mutate(set = names(TreeRatesSet)) %>%
select(-rates)
tipLengths <- cbind.data.frame(edge = treeMCC$edge,
time = treeMCC$edge.length) %>%
filter(edge.2 <= Ntip(treeMCC)) %>%
mutate(species = treeMCC$tip.label,
nodes_sister = ifelse(edge.1 %in% edge.1[duplicated(edge.1)], "sister","nonSister"))
clades <- read.delim(paste0(folder_path,'5.speciation_rate/inputs/MamPhy_5911sp_tipGenFamOrdCladeGenesSampPC.txt')) %>%
drop_na(PC) %>%
mutate(species = word(tiplabel, 1,2, sep = "_"),
clades = sub("^PC\\d+_", "", PC)) %>%
select(species, clades, ord, fam) %>%
filter(species %in% treeMCC$tip.labels)
changeClades <- select(clades, clades) %>%
distinct() %>%
arrange(clades) %>%
filter(clades %in% c("Cetartiodactyla", "EmballonuridRelated",
"GuineaPigRelated","Marsupials", "PhyllostomidRelated",
"SquirrelRelated","VespertilionidRelated")) %>%
mutate(newNames = c("Artiodactyla", "Emballonuroidea",
"Guinea Pig-related","Marsupialia", "Noctilionoidea",
"Squirrel-related", "Vespertilionoidea"))
Nodes <- read.delim(paste0(folder_path,'5.speciation_rate/inputs/Upham_FBD_clades_nodes.txt'))
### to include the clades that had fewer species as an arc in figure 1
for(clade in unique(clades$clades)[!unique(clades$clades) %in% Nodes$clades]){
a <- as.character(clades[clades$clades %in% clade,'species'])
cladeNode <- ape::getMRCA(treeMCC, a)
if(!is.null(cladeNode)){
Nodes <- bind_rows(Nodes, data.frame(clades = clade, node = cladeNode))
}
}
spRate <- read.delim(paste0(folder_path,'5.speciation_rate/outputs/MCCposterior100_tipRate.txt')) %>%
rename(set = treeN ) %>%
left_join(., clades, by = 'species')
gendivSpRate <- spRate %>%
left_join(., select(gen.div, species, EstPiSyn, subPiSyn_mean, EstThetaSyn, subThetaSyn_mean), by = 'species')
traitData <- read.delim(paste0(folder_path,'otherData/traits/matchedTraits_v3.txt'), stringsAsFactors = FALSE) %>%
select(-Family) %>%
mutate(mean_temp = mean_temp + abs(min(mean_temp, na.rm = T)) + 1,
latitude_mean = abs(latitude_mean))
gendivSpRateTrait <- gendivSpRate %>%
left_join(., traitData, by = 'species')
MutRateAll <- readRDS(paste0(folder_path, '6.mutationRate/outputs/mutationRate_cytb3rdcodonPAML.rds'))
gendivSpRateMutRate <- gendivSpRateTrait %>%
left_join(., MutRateAll, by = c('set','species')) %>%
select(-mutrate) %>%
mutate(timeyear = time * 1000000,
GenerationLength_y = GenerationLength_d/365,
mutRate = (expNsub * GenerationLength_y) / timeyear,
Ne = EstPiSyn / mutRate,
mutRate_y = expNsub/timeyear,
Ne_y = EstPiSyn / mutRate_y) %>%
arrange(set)
### Load PGLS results
extract_strings_in_parentheses <- function(text) {
matches <- str_match_all(text, "\\((.*?)\\)")[[1]]
if (is.null(matches))
return(NA_character_)
extracted_strings <- matches[, 2]
return(paste(extracted_strings, collapse = " + "))
}
PGLSglobalAll <- readRDS(paste0(folder_path,'7.pgls/outputs/gendivSpRate_PGLSresultsAll_REML.rds')) %>%
rename(Estimate = 'Value',SE = 'Std.Error', pvalue = 'p.value') %>%
mutate(modelR = sapply(word(modelF, sep = " ~ ",1,1), extract_strings_in_parentheses),
modelP = sapply(word(modelF, sep = " ~ ",2,2), extract_strings_in_parentheses),
term = sapply(term, extract_strings_in_parentheses),
analysisType = case_when(analysis %in% c("piSpRateTraits", "piTraits","SpRateTraits") ~ "global_traits",
analysis %in% c("MutyRateSpRate","NeySpRate") ~ "global_mutRate",
analysis %in% c("EstPiSyn","SubPiSyn","EstThetaSyn","SubThetaSyn") ~ "global",
TRUE ~ "other"))
PGLSclade <- readRDS(paste0(folder_path,'7.pgls/outputs/clade_gendivSpRate_PGLSresults.rds')) %>%
mutate(term = case_when(term %in% '(Intercept)' ~ 'Intercept',
term %in% 'log(tipRate)' ~ 'tipRate')) %>%
rename(pgls_lambda = 'lambda',
pvalue = 'Pr...t..') %>%
select(clade, set, analysis, df, pgls_lambda, term, Estimate, pvalue)
### Load BMLM results
BMLMglobal <- readRDS(paste0(folder_path,'8.bmlm/outputs/global_allPosterior.rds'))
BMLMglobal_traits <- readRDS(paste0(folder_path,'8.bmlm/outputs/global_traits_allPosterior.rds'))
BMLMglobal_mutRate <- readRDS(paste0(folder_path,'8.bmlm/outputs/global_mutRate_allPosterior_year.rds'))
colSet <- data.frame(clades = unique(PGLSclade$clade),
col = iwanthue(length(unique(PGLSclade$clade))))
# Then create cladesSum as before
cladesSum <- data.frame(table(clades$clades),
stringsAsFactors = F) %>%
rename(clades = Var1) %>%
left_join(colSet) %>%
mutate(clades2 = ifelse(clades %in% changeClades$clades,
changeClades$newNames[match(clades, changeClades$clades)],
clades))
```
A total of `r nrow(gen.div)` species with synonymous genetic diversity data were used for most analyses. This corresponds to around `r round(nrow(gen.div)/sum(Nodes$Nsp_complete, na.rm = TRUE)*100,0)`% of sampled mammals species, given the species identified in Upham et. al 2019.
# Figure 1
```{r, fig.width = 7.087, fig.height = 5.45, cache = FALSE}
#### prepare the data ####
tipRatesMCC <- spRate %>%
filter(set %in% "treeMCC") %>%
pull(tipRate)
sub_tree = treeMCC
sub_rates = ratesMCC
rep = map_rates_tipNroot(sub_tree, sub_rates = sub_rates, treeMCC,
rates = rep(NaN, nrow(treeMCC$edge)))
new_rates = rep$rates
clades_root = as.numeric(c(Nodes[Nodes$clades %in% unique(PGLSclade$clade),'node']))
clades_tips = list()
clades_edges = list()
for (i in unique(Nodes$clades)) {
clades_tips[[i]] = getDescendants(sub_tree, Nodes[Nodes$clades %in% i, 'node'])
}
names(clades_tips)[names(clades_tips) %in% changeClades$clades] <- na.omit(changeClades[match(names(clades_tips), changeClades$clades), 2])
pglsSet <- unique(PGLSclade$clade)
pglsSet[pglsSet %in% changeClades$clades] <- na.omit(changeClades[match(pglsSet, changeClades$clades), 2])
#### a few options ####
save_pdf = F
v1_name = "EstPiSyn"
col1_nbins = 100
col1_offset = 20
col1_pal = "YlOrRd"
D = 0.5 # Controls inner spacing to the tree
L1 = 0.7 # Controls length of first set of bars
v2_name = "EstThetaSyn"
col2_nbins = 100
col2_offset = 5
col2_pal = "YlGnBu"
L2 = 0.7
vertical = 1
#### start pdf ####
if(vertical==1){
if (save_pdf) cairo_pdf(paste0(fig_path, 'Figure1_batlow.pdf'), width = 7.087, height = 5.45, family = 'Arial') #useDingbats = FALSE, #width = 18, height = 14,
layout(matrix(c(1,2,1,3), ncol = 2 , byrow = T), widths = c(3,1)) # Keeping original ratio initially
}else if (vertical==2){
if (save_pdf) pdf(paste0("~/Desktop/Figure1_treeSpRateGenDiv.pdf"), width = 12, height = 15)
#layout(matrix(c(1,1,2,3), ncol = 2 , byrow = T), heights = c(3,1))
layout(matrix(c(1,1,3,2), ncol = 2 , byrow = T), heights = c(3,1))
}else if (vertical==3){
if (save_pdf) pdf(paste0("~/Desktop/Figure1_treeSpRateGenDiv.pdf"), width = 12, height = 14)
#layout(matrix(c(1,1,2,3), ncol = 2 , byrow = T), heights = c(3,1))
layout(matrix(c(1,1,2,3), ncol = 2 , byrow = T), heights = c(3,0.6))
}else if (vertical==4){
if (save_pdf) pdf(paste0("~/Desktop/Figure1_treeSpRateGenDiv.pdf"), width = 12, height = 15)
#layout(matrix(c(1,1,2,3), ncol = 2 , byrow = T), heights = c(3,1))
layout(matrix(c(2,1,3), ncol = 1 , byrow = T), heights = c(0.6,3,0.6))
}else if (vertical==5){
if (save_pdf) pdf(paste0("~/Desktop/Figure1_treeSpRateGenDiv.pdf"), width = 12, height = 15)
#layout(matrix(c(1,1,2,3), ncol = 2 , byrow = T), heights = c(3,1))
layout(matrix(c(4,2,1,1,3,5), ncol = 2 , byrow = T), heights = c(0.6,3,0.6))
}
#### plot the tree #####
par(mar = c(2,1,2,0))
plot_tree = treeMCC
plot_tree$tip.label[] = ""
plot_tree$tip.label[1] = "..." # to make the tree smaller, long invisible tip label was added
tipcol = rgb(255,255,255,alpha = 255,maxColorValue = 255)
col_tree= invisible(plot.with.rate.withNaNs(plot_tree,
c(new_rates), NaN_color = "gray90",
leg = F,same.scale = T, lwd = 0.55, # Reduced from 1.5
log = T,
show.tip.label = T, tip.color = tipcol))
#### collect tips coordinates ####
lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv)
tip <- 1:lastPP$Ntip
XX <- lastPP$xx
YY <- lastPP$yy
#### chose tip lines colors ####
col_v1 = c(colorRampPalette((brewer.pal(n = 8, name = col1_pal)))(col1_offset + col1_nbins)) # color palette
v1 = c()
for (i in treeMCC$tip.label){
if (i %in% gen.div$species){
v1 = c(v1,as.numeric(gen.div[gen.div$species == i, v1_name]))
}else{
v1 = c(v1,NA)
}
}
v1_transformed = log(v1+0.005)
range_v1 = range(v1_transformed, na.rm = T)
lab_v1 = c(0,0.01,0.02,0.05,0.1)
at_v1 = log(lab_v1+0.005)
col1 = col_v1[round(( (v1_transformed - range_v1[1]) / (range_v1[2]-range_v1[1]))*(col1_nbins-1) )+col1_offset+1]
#### add them to the tree ####
line_position = D + c(0,L1)
total_depth = sqrt(XX[1]^2 + YY[1]^2)
add2depth = 0.05 * total_depth
for (i in 1:length(treeMCC$tip.label)){
if (! is.na(col1[i])){
addx = add2depth*line_position*XX[i]/total_depth
addy = add2depth*line_position*YY[i]/total_depth
lines(XX[i]+addx, YY[i]+addy, col = col1[i], lwd = 0.55, xpd = T) # Reduced from 1.5
}
}
#### chose tip lines colors / 2nd measure ####
col_v2 = c("#FFFFFF", colorRampPalette((brewer.pal(n = 8, name = col2_pal)))(col2_offset + col2_nbins)) # color palette
v2 = c()
for (i in treeMCC$tip.label){
if (i %in% gen.div$species){
v2 = c(v2,as.numeric(gen.div[gen.div$species == i, v2_name]))
}else{
v2 = c(v2,NA)
}
}
v2_transformed = log(v2+0.005)
range_v2 = range(v2_transformed, na.rm = T)
lab_v2 = c(0,0.01,0.02,0.05,0.1)
at_v2 = log(lab_v2+0.005)
col2 = col_v2[round(( (v2_transformed - range_v2[1]) / (range_v2[2]-range_v2[1]))*(col2_nbins-1) )+col2_offset+1]
#### add them to the tree ####
line_position = D+L1+0.05+c(0,L2)
total_depth = sqrt(XX[1]^2 + YY[1]^2)
add2depth = 0.05 * total_depth
for (i in 1:length(treeMCC$tip.label)){
if (! is.na(col2[i])){
addx = add2depth*line_position*XX[i]/total_depth
addy = add2depth*line_position*YY[i]/total_depth
lines(XX[i]+addx, YY[i]+addy, col = col2[i], lwd = 0.55, xpd = T) # Reduced from 1.5
}
}
### plot nodes of PGLS clades
for (i in clades_root){
points(XX[i], YY[i], col = "red4", bg = "red1", pch = 21, cex = 0.417, lwd = 0.4) # Reduced from 1.2 and 1
}
#### circular arcs for analysed clades ####
l = D + 0.05 + L1 + L2 + D
nCT = length(clades_tips)
clades_names = unique(names(clades_tips))
radius = total_depth + add2depth*(l+D)
add2text = 0.9
further = rep(0,nCT)
further[which(clades_names %in% c("Lagomorpha", "Squirrel-related"))] = add2text
set.seed(1)
grays = Nodes[,c('clades','node')] %>%
mutate(ord = seq(1:nCT)) %>%
arrange(desc(node)) %>%
left_join(., cladesSum, by = 'clades') %>%
arrange(ord) %>%
pull(col, name = clades2)
for (i in 1:nCT){
tips = sort(clades_tips[[i]][clades_tips[[i]] <= (sub_tree$Nnode + 1)])
lt = length(tips)
tips = tips[-((lt-2):lt)] ###why is not working for every clade with more than one species?
tips = tips[-(1:2)]
xs = XX[tips]
ys = YY[tips]
xs = xs + add2depth*l*xs/total_depth
ys = ys + add2depth*l*ys/total_depth
colGray <- ifelse(as.character(clades_names[i]) %in% pglsSet, grays[i], "white") #"gray90"
lines(xs,ys, lwd = 0.8, col = colGray) # Reduced from 3
lt = length(tips)
if(lt > 1){
cl = T
angle_i = acos(xs[floor(lt/2)]/(total_depth + add2depth*l))
if (ys[floor(lt/2)] < 0){
angle_i = -1 * angle_i
cl = F
}
if(as.character(clades_names[i]) %in% pglsSet){
arctext(as.character(clades_names[i]), radius = radius + further[i]*add2depth,
middle = angle_i, col = grays[i], clockwise = cl, cex = 0.583, xpd = T)
}
}
}
#### first densplot ####
clades_tips2 <- clades_tips[names(clades_tips) %in% pglsSet]
rangeX = range(XX)
rangeY = range(YY)
relative_width = 0.4
relative_heigth = 0.35
relative_rangeX = relative_width*rangeX
relative_rangeY = relative_width*rangeY
xrel = function(x,rrX = relative_rangeX, from = 0, to = 1){
newx = from + (to-from)*(x - min(x))/diff(range(x))
newx = newx*diff(rrX) + min(rrX)
return(newx)
}
yrel = function(x,rrX = relative_rangeY, from = 0, to = 1){
newx = from + (to-from)*(x - min(x))/diff(range(x))
newx = newx*diff(rrX) + min(rrX)
return(newx)
}
polygon(relative_rangeX[c(1,1,2,2)],
relative_rangeY[c(1,2,2,1)],
border = NA, col = adjustcolor("white", alpha.f = 0.8))
# plot the density
lower_y = 0.25
densclads = lapply(clades_tips2, function(vect){density(log(ratesMCC[sapply(vect,
function(x){which(treeMCC$edge[,2]==x)})]))})
dens_all = density(log(tipRatesMCC)) #new_rates for all rates and tipRatesMCC for just tip rates
maxy = max(dens_all$y)
for(i in 1:length(densclads)){maxy = max(max(densclads[[i]]$y),maxy)}
newlower_y = yrel(c(0,lower_y,1))[2]
for(i in 1:length(densclads)){
lines(xrel(c(range(dens_all$x),densclads[[i]]$x))[-c(1:2)],
yrel(c(maxy,densclads[[i]]$y), from = lower_y)[-1],
lwd = 0.7, col = grays[i]) # Reduced from 2
}
polygon(xrel(dens_all$x)[c(1,1:length(dens_all$x),length(dens_all$x))],
c(newlower_y,yrel(c(maxy,dens_all$y), from = lower_y)[-1],newlower_y),
border = NA, col = adjustcolor("gray80", alpha.f = 0.5))
lines(xrel(dens_all$x),
yrel(c(maxy,dens_all$y), from = lower_y)[-1],
lwd = 1.2) # speciation rate density line
# add the color legend
axis_y = 0.15
col_x = xrel(c(range(diff(log(ratesMCC))),
min(dens_all$x)+c(diff(range(dens_all$x))*(0:length(col_tree$col))/length(col_tree$col))))[-c(1,2)]
col_y = yrel(c(0,1), from = axis_y + 0.005, to = lower_y - 0.05)
for(i in 1:length(col_tree$col)){
polygon(col_x[c(i,i+1)][c(1,1,2,2)], col_y[c(1,2,2,1)],
border = col_tree$col[i], col = col_tree$col[i])
}
# add the axis
lines(relative_rangeX, yrel(c(0,0,1), from = axis_y)[1:2], lwd = 0.5) # Reduced from 2
lab = c(0.03,0.05,0.1,0.2,0.5,1)
ticks = xrel(sort(c(range(dens_all$x),
log(lab))))
# text(0,relative_rangeY[1]+5,expression(Speciation~rates~"("~Myr^"-1"~")"),
# cex = 0.583) # Set to ~7pt
for (i in 2:(1+length(lab))){
lines(ticks[c(i,i)],
yrel(c(0,1), from = axis_y-0.015, to = axis_y + 0.015),
lwd = 0.5) # Reduced from 1.5
text(labels = lab[i-1],
x = ticks[i],
y = yrel(c(0,1), from = axis_y-0.05, to = axis_y + 0.015)[1],
cex = 0.417) # Set to ~5pt
}
#### densities for Pi ####
par(mar = c(0, 2, 4, 1))
plot(1000, xlim = c(-1,1), ylim = c(-1,1), axes = F, xlab = "", ylab = "")
lower_y = 0.25
#### First measure ####
relative_rangeX = c(0,1)
relative_rangeY = c(-1,1)*1 # Try reducing to 0.75 to make plots more vertically compact
dens_all1 = density(v1_transformed, na.rm = T)
dens_all2 = density(v2_transformed, na.rm = T)
ry = range(c(dens_all1$x,dens_all2$x,-6.5,-1))
xrel = function(x,rrX = relative_rangeX, from = 0, to = 1){
newx = from + (to-from)*(x - min(x))/diff(range(x))
newx = newx*diff(rrX) + min(rrX)
return(newx)
}
yrel = function(x,rrX = relative_rangeY, from = 0, to = 1,My = ry[2],my = ry[1]){
newx = from + (to-from)*(x - my)/(My-my)
newx = newx*diff(rrX) + min(rrX)
return(newx)
}
dens_all = density(v1_transformed, na.rm = T)
densclads = lapply(clades_tips2, function(vect){density(v1_transformed[vect[vect<4065]], na.rm = T)})
maxy = max(dens_all$y)
for(i in 1:length(densclads)){maxy = max(max(densclads[[i]]$y),maxy)}
newlower_y = xrel(c(0,lower_y,1))[2]
for(i in 1:length(densclads)){
lines(y = yrel(c(range(dens_all$x),densclads[[i]]$x))[-c(1:2)],
x = -xrel(c(maxy,densclads[[i]]$y), from = lower_y)[-1],
lwd = 0.7, col = grays[i]) # Reduced from 2
}
polygon(y = yrel(dens_all$x)[c(1,1:length(dens_all$x),length(dens_all$x))],
x = -c(newlower_y,xrel(c(maxy,dens_all$y), from = lower_y)[-1],newlower_y),
border = NA, col = adjustcolor("gray80", alpha.f = 0.5))
lines(y = yrel(dens_all$x),
x = -xrel(c(maxy,dens_all$y), from = lower_y)[-1],
lwd = 1.2) # Reduced from 3
#### Second measure ####
dens_all = density(v2_transformed, na.rm = T)
densclads = lapply(clades_tips2, function(vect){density(v2_transformed[vect[vect<4065]], na.rm = T)})
maxy = max(dens_all$y)
for(i in 1:length(densclads)){maxy = max(max(densclads[[i]]$y),maxy)}
for(i in 1:length(densclads)){
lines(y = yrel(c(range(dens_all$x),densclads[[i]]$x))[-c(1:2)],
x = xrel(c(maxy,densclads[[i]]$y), from = lower_y)[-1],
lwd = 0.7, col = grays[i]) # Reduced from 2
}
polygon(y = yrel(dens_all$x)[c(1,1:length(dens_all$x),length(dens_all$x))],
x = c(newlower_y,xrel(c(maxy,dens_all$y), from = lower_y)[-1],newlower_y),
border = NA, col = adjustcolor("gray80", alpha.f = 0.5))
lines(y = yrel(dens_all$x),
x = xrel(c(maxy,dens_all$y), from = lower_y)[-1],
lwd = 1.2) # Reduced from 3
# add the color legends
axis_y = 0.15
c1 = col_v1
col_x = yrel(range_v1[1]+diff(range_v1)*(0:length(c1))/length(c1))
col_y = xrel(c(0,1), from = axis_y + 0.005, to = lower_y - 0.05)
for(i in 1:length(c1)){
polygon(y = col_x[c(i,i+1)][c(1,1,2,2)], x = -col_y[c(1,2,2,1)],
border = c1[i], col = c1[i])
}
polygon(y = c(relative_rangeY[1],col_x[1])[c(1,1,2,2)], x = -col_y[c(1,2,2,1)],
border = c1[1], col = c1[1])
lx = length(c1)
polygon(y = c(relative_rangeY[2],col_x[lx])[c(1,1,2,2)], x = -col_y[c(1,2,2,1)],
border = c1[lx], col = c1[lx])
c2 = col_v2
col_x = yrel(range_v2[1]+diff(range_v2)*(0:length(c2))/length(c2))
col_y = xrel(c(0,1), from = axis_y + 0.005, to = lower_y - 0.05)
for(i in 1:length(c2)){
polygon(y = col_x[c(i,i+1)][c(1,1,2,2)], x = col_y[c(1,2,2,1)],
border = c2[i], col = c2[i])
}
polygon(y = c(relative_rangeY[1],col_x[1])[c(1,1,2,2)], x = col_y[c(1,2,2,1)],
border = c2[2], col = c2[2])
lx = length(c2)
polygon(y = c(relative_rangeY[2],col_x[lx])[c(1,1,2,2)], x = col_y[c(1,2,2,1)],
border = c2[lx], col = c2[lx])
#### axis ####
lines(y = relative_rangeY, x = c(axis_y,axis_y), lwd = 0.5) # Reduced from 2
lines(y = relative_rangeY, x = -c(axis_y,axis_y), lwd = 0.5) # Reduced from 2
lab = c(0.0001,0.002,0.005,0.01,0.02,0.05,0.1,0.2)
ticks = yrel(sort(c(range(dens_all$x), log(lab+0.005))))
for (i in 2:(1+length(lab))){
lines(y = ticks[c(i,i)], x = axis_y+c(-0.015, 0.015), lwd = 0.5) ## tick
text(labels = lab[i-1], y = ticks[i], x = 0, cex = 0.417) # Set to ~5pt
lines(y = ticks[c(i,i)], x = -axis_y+c(-0.015, 0.015), lwd = 0.5) # Reduced from 1.5
}
# Final labels
# text(lab = expression(paste(theta['Tsyn'])),
# x = -0.2, y = 0.9, cex = 0.417) # Set to ~5pt
# text(lab = expression(paste(theta['Wsyn'])),
# x = 0.2, y = 0.9, cex = 0.417) # Set to ~5pt
# text(lab = "Genetic Diversity",
# x = 0, y = 1, cex = 0.583) # Set to ~7pt
#### close pdf ####
if (save_pdf) dev.off()
```
<div class = "figure">
**Figure 1.** Mammals species-level consensus phylogeny from Upham et al. (2019), with branches coloured with branch-specific speciation rates estimated with ClaDS2 (see color legend in the central inset). Bars at tips reflect estimated within-species genetic diversity for those species with 5 or more cytochrome-b sequences available: Tajima’s $\theta_{Tsyn}$ (inner circle, red color legend in the top right inset) and Watterson’s $\theta_{Wsyn}$ (outer circle, blue color legend). Central inset: distribution of tip speciation rates for all mammals (black line, shaded fill) and 14 clades with more than 20 species (coloured lines, no fill); Top-right inset: distribution of genetic diversity, log scaled following the same line colouration. Silhouette figures were contributed by various authors with a public domain license (public domain mark 1.0; CC0 1.0) from PhyloPic (http://phylopic.org). Source data are provided as a source data file.
</div>
****
# Figure 2
```{r,fig.width = 7.087, fig.height = 4.847}
#### label clades that were used for PGLS analyses
mGendivSpRate <- spRate %>%
filter(!set %in% 'treeMCC') %>%
group_by(species) %>%
reframe(rate_mean = mean(tipRate, na.rm = TRUE),
rate_sd = sd(tipRate, na.rm = TRUE),
rate_se = rate_sd / sqrt(n()),
rate_lower.ci = CI(tipRate, ci = 0.95)[1],
rate_upper.ci = CI(tipRate, ci = 0.95)[3],
clades = unique(clades)) %>%
arrange(clades) %>%
mutate(ord = seq(1,length(n)),
species = forcats::fct_reorder(species, ord),
clades = forcats::fct_relevel(case_when(!clades %in% unique(PGLSclade$clade) ~ "Other",
TRUE ~ clades),"Other", after = 14)) %>%
inner_join(.,select(gen.div, species, EstPiSyn, EstThetaSyn, Nind), by = 'species')
tcol0 <- cladesSum %>%
filter(clades %in% mGendivSpRate$clades) %>%
bind_rows(., data.frame(clades = 'Other',col = "gray90"))
tcol <- c( "black",as.character(tcol0[,3]))
names(tcol) <- c("All Mammals", as.character(tcol0[,1]))
pglsSet2 <- pglsSet
names(pglsSet2) <- levels(droplevels(filter(mGendivSpRate, !clades %in% 'Other'))$clades)
mGendivSpRate2 <- mGendivSpRate
mGendivSpRate2$clades2 <- "Mammals"
mGendivSpRate3 <- filter(mGendivSpRate, !clades %in% 'Other') %>%
mutate(clades2 = clades) %>%
bind_rows(mGendivSpRate2) %>%
mutate(clades2 = fct_relevel(clades2, "Mammals", after = 0))
pgls2 <- bind_rows(PGLSglobalAll, PGLSclade) %>%
mutate(clades2 = fct_relevel(case_when(is.na(clade) ~ 'Mammals',
TRUE ~ clade), "Mammals", after = 0),
label = paste0('MCC PGLS:\nEstimate = ',
round(Estimate,3),
'\np-value = ', formatC(pvalue,
format = "E", digits = 2))) %>%
filter(term %in% 'tipRate',
set %in% "treeMCC",
analysis %in% 'EstPiSyn') %>%
select(c('clade','set','analysis','df','Estimate','pvalue','clades2', 'label')) %>%
arrange(analysis)
pglsSet2 <- paste(c('All Mammals', pglsSet), '-', pgls2$df)
names(pglsSet2) <- levels(mGendivSpRate3$clades2)
q2 <- ggplot(data = mGendivSpRate3,
aes(y = EstPiSyn, x = rate_mean)) +
geom_errorbarh(aes(xmin = rate_lower.ci, color = clades2,
xmax = rate_upper.ci), linewidth = 0.2,
alpha = 1, show.legend = F) +
scale_y_continuous(trans='log10',
labels = trans_format("log10", math_format(10^.x))) +
scale_x_continuous(trans='log10') +
geom_smooth(aes(y = EstPiSyn, x = rate_mean), fill = "blue",
color = "black", alpha = 0.1, linetype = "dashed",
method=lm, position = "identity", linewidth = 0.3,
fullrange = FALSE) +
scale_colour_manual(values = tcol[-16]) +
labs(y = expression(paste("Genetic diversity (",theta['Tsyn'],")")),
x = bquote('Speciation rate ' ~ (Myr^-1))) +
facet_wrap(~clades2, ncol = 5,
labeller = labeller(clades2 = pglsSet2)) +
geom_text(aes(x=0.025, y=0.000133, label = label), data = pgls2,
size = 5, hjust = 'left', lineheight = 0.9, family = fon,
size.unit = 'pt' ) +
theme_bw(base_family = fon) +
theme(plot.margin = unit(c(0.1,0.1,0.1,0.1), "cm"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.spacing.x = unit(0.1, "lines"),
panel.spacing.y = unit(0.1, "lines"),
strip.text = element_text(size = 7, face = 'bold',
margin = margin(0.1,0,0.1,0, "cm")),
strip.placement.x = "inside",
strip.background = element_rect(fill = 'white'),
axis.text = element_text(size = 5),
axis.title = element_text(size = 6),
axis.ticks = element_line(linewidth = 0.3),
axis.ticks.length = unit(0.8, "mm"))
# showtext::showtext_auto(FALSE)
# ggsave(paste0(fig_path, "Figure2.pdf"), q2, width = 180, height = 123.12, units = "mm", device = cairo_pdf) #width = 9.5, height = 6.5
# ggsave(paste0(fig_path, "Figure2.png"), q2, width = 180, height = 123.12, units = "mm", device = png, type = 'cairo-png')
# showtext::showtext_auto(TRUE)
q2
```
<div class = "figure">
**Figure 2.** Relationship between intraspecific genetic diversity (Tajima’s $\theta_{Tsyn}$) and speciation rate across all mammals and for each of the 14 clades with at least 20 species. The number of species included in each analysis is indicated. Speciation rates represented by their 95% confidence intervals (CIs) from 100 posterior trees; CIs are very narrow, demonstrating that estimates vary little across posterior trees. Results of the PGLS analyses on the consensus MCC tree are provided and linear regression lines with 95% confidence intervals are shown in purple for visualization purposes. Axes are log scaled. Source data are provided as a source data file.
</div>
****
# Figure 3
```{r, eval = TRUE, fig.height = 4.331, fig.width = 3.465, out.width = "200%"}
pglsResult <- bind_rows(PGLSglobalAll, PGLSclade) %>%
filter(!set %in% 'treeMCC',
term %in% 'tipRate',
analysis %in% 'EstPiSyn') %>%
mutate(.variable = ifelse(is.na(clade), 'All Mammals', clade),
pvalueBin = ifelse(pvalue < 0.05, 'Signif.','Not signif.')) %>%
select(clade, .variable, set, Estimate, pvalue, pvalueBin)
gl <- BMLMglobal %>%
filter(.chain %in% 1, model %in% 'EstPiSyn', !set %in% 'treeMCC') %>%
select(-.value, -.variable, -r_clades, -.chain,-.iteration,-.draw) %>%
rename(.value = b_logtipRate) %>%
mutate(.variable = 'All Mammals') %>%
distinct() ##around 1000 unique samples per tree set
cl <- BMLMglobal %>%
filter(.chain %in% 1, model %in% 'EstPiSyn', !set %in% 'treeMCC') %>%
select(-.chain,-.iteration,-.draw,-r_clades, -b_logtipRate) %>%
distinct()
BMLMglobalPi <- bind_rows(gl,cl) ## makes it easier to export the data for source file
pp1 <- ggplot(filter(BMLMglobalPi, .variable %in% 'All Mammals'),
aes(x = .value, y = fct_rev(.variable))) +
geom_vline(aes(xintercept = 0), linetype= 2, linewidth = 0.3) +
stat_halfeye(fill = "gray80", point_interval = median_hdi, linewidth = 0.025, size = 1, stroke = 0,
.width = .95, alpha = 1, scale = 0.7) +
xlim(-2.14, 1.02) +
geom_point(data = filter(pglsResult, .variable %in% 'All Mammals'),
aes(x = Estimate, y = fct_rev(.variable),
colour = pvalueBin), alpha = 0.7, size = 1.2, shape = 20, stroke = 0,
position = position_nudge(y = -0.15), show.legend = F) +
scale_color_manual(values = c('red','gray80')) +
theme_bw(base_family = fon) +
theme(axis.ticks = element_line(linewidth = 0.25),
axis.ticks.length = unit(0.5, "mm"),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
panel.border = element_rect(linewidth = 0.25),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
text = element_text(size=7), plot.margin = margin(t = 5, b = 0))
pp2 <- ggplot(filter(BMLMglobalPi, !.variable %in% 'All Mammals'),
aes(x = .value, y = fct_rev(.variable))) +
geom_vline(aes(xintercept = 0), linetype= 2, linewidth = 0.3) +
stat_halfeye(fill = "gray80", point_interval = median_hdi, linewidth = 0.025, size = 1, stroke = 0,
.width = .95, alpha = 1, scale = 0.7, show.legend = F ) +
scale_y_discrete(labels=rev(pglsSet)) +
geom_point(data = filter(pglsResult, !.variable %in% 'All Mammals'),
aes(x = Estimate, y = fct_rev(.variable),
colour = pvalueBin), alpha = 0.7, size = 1.2, shape = 20, stroke = 0,
position = position_nudge(y = -0.15), show.legend = F) +
scale_colour_manual(values = c('gray80','red')) +
labs(x = "Slope Estimates") +
xlim(-2.14, 1.02) +
theme_bw(base_family = fon) +
theme(axis.ticks = element_line(linewidth = 0.25),
axis.ticks.length = unit(0.5, "mm"),
axis.title.y=element_blank(),
axis.text.y = element_text(colour = rev(tcol[2:15])),
axis.text.x = element_text(size = 5),
axis.title.x = element_text(size = 6),
panel.border = element_rect(linewidth = 0.25),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
text = element_text(size=7))
# p3 = ggarrange(pp1, pp2, nrow = 2, heights = c(0.3, 2), align = "v")
p3 = pp1 / pp2 +
plot_layout(heights = c(0.2, 2)) +
theme(plot.margin = margin(0,0,0,0))
# showtext::showtext_auto(FALSE)
# ggsave(paste0(fig_path, 'Figure3.pdf'), p3, height = 110, width = 88, units = "mm", device = cairo_pdf)
# ggsave(paste0(fig_path, 'Figure3.png'), p3, height = 110, width = 88, units = "mm", device = png, type = 'cairo-png')
# showtext::showtext_auto(TRUE)
p3
```
<div class = "figure">
**Figure 3.** Slope estimates of the relationship between intraspecific genetic diversity ($\theta_{Tsyn}$) and speciation rates for all mammals (top panel) and each of the 14 clades with at least 20 species (bottom panel). The grey density plots with median point and 95% confidence intervals in black represent the estimated posterior distribution of slopes obtained with the Bayesian Multilevel Models (BMLM) pulled across 100 trees. The points below represent the slopes estimated with Phylogenetic Generalized Least Squares analyses conducted on each of the 100 trees and are coloured in red when significant (p-value < 0.05). Source data are provided as a source data file.
</div>
****
# Table 1
```{r, cache = TRUE, results='asis'}
pglsResulttraitsMCC <- PGLSglobalAll %>%
filter(analysisType %in% 'global_traits',
set %in% 'treeMCC',
!term %in% 'Intercept') %>%
ungroup() %>%
mutate(`p-value` = ifelse(pvalue < 0.001, "<0.001", round(pvalue,4)),
term = recode(term, tipRate = !! "\u03BB",
latitude_mean = "Mean latitude",
mean_temp = "Mean temperature",
#geoArea = "Range area",
BodyMassKg_notInputed = "Body Mass",
GenerationLength_d = "Generation length",
litter_or_clutch_size_n = "Litter size"),
ana = 'PGLS') %>%
select(analysis, Estimate, term,SE, pvalue, ana)
BMLMglobal_traitsExt <- BMLMglobal_traits %>%
select(-.chain,-.iteration,-.draw) %>%
rename(term = .variable, Estimate = .value, analysis = model) %>%
mutate(ana = 'BMLM')
BMLMglobal_traitsExtMCC <- filter(BMLMglobal_traitsExt, set %in% 'treeMCC') %>%
group_by(term, analysis) %>%
median_qi(Estimate) %>%
mutate(term = recode(term, b_logtipRate = !! "\u03BB",
b_loglatitude_mean = "Mean latitude",
b_logmean_temp = "Mean temperature",
b_logBodyMassKg_notInputed = "Body Mass",
b_logGenerationLength_d = "Generation length",
b_loglitter_or_clutch_size_n = "Litter size"),
ana = 'BMLM',
`95% CI` = paste0("[",round(.lower,3),"; ",round(.upper,3),"]"),
sign95 = case_when(Estimate > 0 & .lower > 0 & .upper > 0 ~ "sign.",
Estimate < 0 & .lower < 0 & .upper < 0 ~ "sign.",
TRUE ~ "NotSign.")) %>%
select(-(.lower:.interval))
BMLMPGLSmcc <- bind_rows(pglsResulttraitsMCC,
select(BMLMglobal_traitsExtMCC, -sign95)) %>%
mutate(term = ifelse(term == "Mean latitude", "Latitudinal midpoint", term)) %>%
mutate(term = fct_relevel(term,!! "\u03BB", "Latitudinal midpoint", "Mean temperature",
"Body Mass", "Generation length", "Litter size")) %>%
mutate_if(is.numeric, round, 3) %>%
pivot_wider(names_from = ana,
values_from = c(Estimate, SE, pvalue, `95% CI`)) %>%
dplyr::select(-c("SE_BMLM","pvalue_BMLM","95% CI_PGLS")) %>%
relocate(Estimate_BMLM, .before = "95% CI_BMLM") %>%
pivot_wider(names_from = analysis,
values_from = Estimate_PGLS:`95% CI_BMLM`)
BMLMPGLSmccRed <- BMLMPGLSmcc[,c(1,3,6,9,12,15,
4,7,10,13,16,
2,5,8,11,14)] %>%
select(-starts_with("pvalue")) %>%
arrange(term)
ps <- BMLMPGLSmcc %>%
arrange(match(term, BMLMPGLSmccRed$term)) %>% ## arranges order according to levels
select(starts_with("pvalue"))
bs <- select(BMLMglobal_traitsExtMCC, term, analysis, sign95) %>%
pivot_wider(names_from = analysis,
values_from = sign95) %>%
arrange(match(term, BMLMPGLSmccRed$term))
typology <- tibble(col_keys = names(BMLMPGLSmccRed),
name = names(BMLMPGLSmccRed)) %>%
separate(name, sep = "_" , into = c('stat', 'analysis', 'model'))
ft <- autofit(flextable(BMLMPGLSmccRed)) %>%
set_header_df(mapping = typology[,c(1,4,3,2)], key = "col_keys" ) %>%
merge_h(part = "header") %>%
merge_v(part = "header") %>%
flextable::compose(i = 1, j = 2, part = "header", value = as_paragraph("\U03B8", as_sub("T"), " ~ Traits")) %>%
flextable::compose(i = 1, j = 6, part = "header", value = as_paragraph("\u03BB", " ~ Traits")) %>%
flextable::compose(i = 1, j = 10, part = "header", value = as_paragraph("\U03B8", as_sub("T"), " ~ ", "\u03BB", " + Traits")) %>%
colformat_num(j = colnames(BMLMPGLSmccRed), na_str = "", digits = 3) %>%
theme_booktabs(fontsize = 10) %>%
fix_border_issues() %>%
align_nottext_col(align = "center", header = TRUE) %>%
vline(j = 3, border = officer::fp_border(), part = "all") %>%
vline(j = 5, border = officer::fp_border(width = 2), part = "all") %>%
vline(j = 7, border = officer::fp_border(), part = "all") %>%
vline(j = 9, border = officer::fp_border(width = 2), part = "all") %>%
vline(j = 11, border = officer::fp_border(), part = "all") %>%
bold(j = 1, part = 'all') %>%
bold(j = 2, i = which(ps$pvalue_PGLS_piTraits < 0.05), part = 'body') %>%
bold(j = 6, i = which(ps$pvalue_PGLS_SpRateTraits < 0.05), part = 'body') %>%
bold(j = 10, i = which(ps$pvalue_PGLS_piSpRateTraits < 0.05), part = 'body') %>%
bold(j = 4, i = which(bs$piTraits %in% 'sign.'), part = 'body') %>%
bold(j = 8, i = which(bs$SpRateTraits %in% 'sign.'), part = 'body') %>%
bold(j = 12, i = which(bs$piSpRateTraits %in% 'sign.'), part = 'body') %>%
add_footer_lines("PGLS and BMLM analyses on the MCC tree. PGLS and BMLM estimates in bold are significantly different from zero (p<0.05)")
#save_as_image(ft, path = paste0(fig_path,"table1.png"))
ft
```
<div class = "table">
**Table 1.** Correlations between genetic diversity ($\theta_{Tsyn}$), speciation rates ($\lambda$) and species-specific covariates. The left and middle columns report results for the association between $\theta_{Tsyn}$ (respectively ) and each covariate from the combined analysis. The right column reports results for the association between $\theta_{Tsyn}$ and $\lambda$ when accounting for all covariates (top row), and between $\theta_{Tsyn}$ and each covariate when accounting for and other covariates (bottom rows). PGLS and BMLM analyses on the MCC tree.
</div>
****
# Figure 4
```{r, fig.height = 2.992, fig.width = 3.464, cache = FALSE, out.width = "200%"}
pglsResultMR <- PGLSglobalAll %>%
filter(!term %in% 'intercept', analysisType %in% 'global_mutRate') %>%
mutate(pvalueBin = ifelse(pvalue < 0.05, 'Signif.','Not signif.'),
ana = 'PGLS') %>%
select(analysis, set, Estimate, term, pvalue, pvalueBin, ana) %>%
data.frame()
pglsResultMR$analysis <- factor(pglsResultMR$analysis, ###"MutyRateSpRate" "NeySpRate"
labels = c(expression(paste(mu,' ~ ', lambda)),
expression(paste(N["e"], ' ~ ', lambda))))
BMLMglobal_mutRateExt <- BMLMglobal_mutRate %>%
select(-.chain,-.iteration,-.draw) %>%
rename(term = .variable, Estimate = .value, analysis = model) %>%
mutate(term = case_when(term %in% "b_logtipRate" ~ "tipRate"),
ana = 'BMLM') %>%
data.frame()
BMLMglobal_mutRateExt$analysis <- factor(BMLMglobal_mutRateExt$analysis,
labels = c(expression(paste(mu,' ~ ', lambda)),
expression(paste(N["e"],' ~ ', lambda))))
sumBMLM <- BMLMglobal_mutRateExt %>%
group_by(term, analysis, set) %>%
median_qi(Estimate) %>%
rename(medianEstimate = Estimate)
dt <- filter(BMLMglobal_mutRateExt, !set %in% 'treeMCC',
analysis %in% c('paste(mu, " ~ ", lambda)',
'paste(N["e"], " ~ ", lambda)'))
blmlplot1 <- ggplot(dt) +
stat_halfeye(aes(x = Estimate, y = term),
point_interval = median_qi, linewidth = 0.3, stroke = 0,
.width = .95, size = 1.3, alpha = 1) +
geom_pointintervalh(data = filter(sumBMLM, set %in% 'treeMCC',
analysis %in% c('paste(mu, " ~ ", lambda)',
'paste(N["e"], " ~ ", lambda)')),
aes(x = medianEstimate, y = term,
xmin =.lower, xmax = .upper),
shape = 17, size = 1, linewidth = 0.2, stroke = 0,
fatten_point = 3, position = position_nudge(y = -0.7)) +
geom_point(data = filter(pglsResultMR, !set %in% 'treeMCC', term %in% 'tipRate',
analysis %in% c('paste(mu, " ~ ", lambda)',
'paste(N["e"], " ~ ", lambda)')),
aes(x = Estimate, y = term, color = pvalueBin),
size = 1.2, show.legend = F, alpha = 0.4, stroke = 0,
position = position_nudge(y = -0.2)) +
scale_colour_manual(values=c('gray80','red')) +
geom_point(data = filter(pglsResultMR, set %in% 'treeMCC', term %in% 'tipRate',
analysis %in% c('paste(mu, " ~ ", lambda)',
'paste(N["e"], " ~ ", lambda)')),
aes(x = Estimate, y = term, color = pvalueBin),
size = 2, show.legend = F, alpha = 0.5, shape = 17, stroke = 0,
position = position_nudge(y = -0.9)) +
geom_vline(aes(xintercept = 0), linetype= 2, linewidth = 0.3) +
facet_wrap(~fct_rev(analysis), labeller = label_parsed, ncol = 1,
strip.position = "right") +
theme_bw() + xlim(-0.82,0.22) +
labs(x = "Slope Estimates") +
theme(axis.ticks = element_line(linewidth = 0.25),,
axis.ticks.length = unit(0.5, "mm"),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.text = element_text(size = 5),
axis.title.x = element_text(size = 6),
strip.text.y.right = element_text(size = 7, margin = margin(l = 0, r = 0)),
strip.background = element_rect(fill = NA),
panel.spacing = unit(0.3, "mm"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.margin = margin(0, 0, 0, 0))
mgendivSpRateMutRate <- gendivSpRateMutRate %>%
filter(!set %in% 'treeMCC') %>%
group_by(species) %>%
dplyr::summarise(SpRate_mean = mean(tipRate, na.rm = TRUE),
SpRate_lower.ci = CI(tipRate, ci = 0.95)[1],
SpRate_upper.ci = CI(tipRate, ci = 0.95)[3],
MutRate_mean = mean(mutRate_y, na.rm = TRUE),
MutRate_lower.ci = CI(mutRate_y, ci = 0.95)[1],
MutRate_upper.ci = CI(mutRate_y, ci = 0.95)[3],
Ne_mean = mean(Ne_y, na.rm = TRUE),
Ne_lower.ci = CI(Ne_y, ci = 0.95)[1],
Ne_upper.ci = CI(Ne_y, ci = 0.95)[3],