-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path01_TaxonomicTree.R
442 lines (355 loc) · 16 KB
/
01_TaxonomicTree.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
# *********************************
# Purpose: Taxonomic tree plotting
# Date: August 2021
# Author: Salomé Carcy
# *********************************
# **************
# 1. IMPORT ####
# **************
## 1.1. Libraries ####
library(phyloseq)
library(ggplot2)
library(tidyverse)
library(treeio)
library(trac)
library(ggtree)
library(ggnewscale)
library(RColorBrewer)
library(scales)
## 1.2. Data ####
path.root <- "~/Projects/MetaIBS" # CHANGE THIS ROOT DIRECTORY ON YOUR COMPUTER
path.phylobj <- file.path(path.root, "data/phyloseq-objects/phyloseq-without-phylotree")
datasets <- list.files(path.phylobj, pattern=".rds")
phyloseqobjects <- sapply(datasets, function(x) readRDS(file.path(path.phylobj, x)), USE.NAMES=T, simplify=F)
# names(phyloseqobjects) # sanity check
# ***********************
# 2. PREPROCESS DATA ####
# ***********************
# Merge phyloseq objects
physeq.all <- merge_phyloseq(phyloseqobjects[[1]], phyloseqobjects[[2]]) # Merge first two phyloseq objects in the list
# if there are more than 2 phyloseq objects, merge the rest of them
if(length(phyloseqobjects)>2){
for (i in 3:length(phyloseqobjects)){
print(paste0("merging with phyloseq object #", i))
physeq.all <- merge_phyloseq(physeq.all, phyloseqobjects[[i]])
}
}
# Separate fecal & sigmoid samples
physeq.fecal <- subset_samples(physeq.all, sample_type == 'stool') # 2,228 samples
physeq.fecal <- prune_taxa(taxa_sums(physeq.fecal)>0, physeq.fecal) # remove ASVs that are not present anymore
physeq.sigmoid <- subset_samples(physeq.all, sample_type == 'sigmoid') # 431 samples
physeq.sigmoid <- prune_taxa(taxa_sums(physeq.sigmoid)>0, physeq.sigmoid) # remove ASVs that are not present anymore
cat("Nb of fecal samples:", nsamples(physeq.fecal))
cat("Nb of sigmoid samples:", nsamples(physeq.sigmoid))
# ************************
# 3. DEFINE FUNCTIONS ####
# ************************
#______________________________________________
## 3.1. Transform tax table to phylo object ####
# This function is copied from https://github.com/jacobbien/trac/blob/master/R/getting_A.R
# tax_table_to_phylo <- function (x, data = parent.frame(), collapse = TRUE, ...) {
# err <- "Formula must be of the kind ~A1/A2/.../An."
# if (any(lapply(data, class) != "factor"))
# stop("Every column of data must be a factor.")
# if (length(x) != 2)
# stop(err)
# if (x[[1]] != "~")
# stop(err)
# f <- x[[2]]
# taxo <- list()
# while (length(f) == 3) {
# if (f[[1]] != "/")
# stop(err)
# f3.txt <- deparse(f[[3]])
# if (!is.factor(data[[f3.txt]]))
# stop(paste("Variable", f3.txt, "must be a factor"))
# taxo[[f3.txt]] <- data[[f3.txt]]
# if (length(f) > 1)
# f <- f[[2]]
# }
# f.txt <- deparse(f)
# if (!is.factor(data[[f.txt]]))
# stop(paste("Variable", f.txt, "must be a factor."))
# taxo[[f.txt]] <- data[[f.txt]]
# taxo.data <- as.data.frame(taxo)
# leaves.names <- as.character(taxo.data[, 1])
# taxo.data[, 1] <- 1:nrow(taxo.data)
# f.rec <- function(subtaxo) {
# u <- ncol(subtaxo)
# levels <- unique(subtaxo[, u])
# if (u == 1) {
# if (length(levels) != nrow(subtaxo))
# warning("leaves names are not unique.")
# return(as.character(subtaxo[, 1]))
# }
# t <- character(length(levels))
# for (l in 1:length(levels)) {
# x <- f.rec(subtaxo[subtaxo[, u] == levels[l], ][1:(u-1)])
# t[l] <- paste0("(", paste(x, collapse = ","), ")", "'", levels[l], "'")
# }
# t
# }
# string <- paste0(f.rec(taxo.data), ";")
# #string <- paste0("(", paste(f.rec(taxo.data), collapse = ","), ");")
# phy <- ape::read.tree(text = string)
# if (collapse)
# phy <- ape::collapse.singles(phy)
# phy$tip.label <- leaves.names[as.numeric(phy$tip.label)]
# phy
# }
#_________________________________
## 3.2. Get a treedata object ####
phyloseq_to_treedata <- function(physeq){
## ***********************
## 1 - GET TAXONOMIC TABLE
tax <- physeq@[email protected][,1:6] # don't include Species
# Add a "Life" column (rank0)
tax <- cbind("Life", tax)
colnames(tax)[1] <- "Life"
# tax[1:5,1:7]
## ***********************
## 2 - GET TAXONOMIC TABLE WITH CUMULATIVE LABELS
full_tax <- tax
for (i in 2:7) {
full_tax[, i] <- paste(full_tax[, i-1], full_tax[, i], sep = "::")
}
full_tax <- as.data.frame(full_tax, stringsAsFactors = TRUE)
# full_tax[1:5,1:7]
## ***********************
## 3 - GET PHYLO OBJECT
tree.phylo <- tax_table_to_phylo(~Life/Kingdom/Phylum/Class/Order/Family/Genus,
data = full_tax, collapse = TRUE)
## ***********************
## 4 - GET TREEDATA OBJECT
# We will define new labels for the tips
d <- data.frame(label=full_tax$Genus,
new_label=tax[,"Genus"],
phylum=tax[,"Phylum"])
d[!d$phylum %in% c("Actinobacteriota", "Bacteroidota", "Firmicutes", "Proteobacteria", "Verrucomicrobiota"), "phylum"] <- "Other"
# Create a treedata object, that will contain the new_label
tree.td <- full_join(tree.phylo, d, by="label")
# Get the list of tip labels belonging to each phylum (phyla are the names of the elements in the list)
l <- list()
for (phylum in unique(d$phylum)){
print(phylum)
l[[phylum]] <- d[d$phylum==phylum,"label"]
}
# Group the nodes and edges by phylum (to color the branches by phylum)
tree.td <- groupOTU(tree.td, l)
## ***********************
## 5 - RETURN TREEDATA OBJECT
return(tree.td)
}
#_________________________________
## 3.3. Function to get dataframe with information on number of ASVs detected for each genus ####
nb_ASV_per_genus <- function(physeq){
asvGenus.df <- as.data.frame(tax_table(physeq)) %>%
rownames_to_column("ASV") %>%
# get a column with Life::Kingdom::Phylum::Class::Order::Family::Genus
mutate(leaf = paste("Life", Kingdom, Phylum, Class, Order, Family, Genus, sep = "::")) %>%
select(ASV, Genus, leaf) %>%
# get nb of ASV per genus
group_by(leaf, Genus) %>%
summarize(n_ASV = n_distinct(ASV)) %>%
# about 30,851 ASVs belong to an unknown genus
filter(!is.na(Genus))
asvGenus.df <- data.frame(n_ASV=asvGenus.df$n_ASV,
row.names = asvGenus.df$leaf)
# Return df
return(asvGenus.df)
}
#______________________
# Function to get a dataframe with information on average count per sample for each genus
count_per_genus <- function(physeq){
# Get relative counts (common-scale normalization: sum per sample==100)
cat("Common-scale normalization...\n")
physeq.CSN <- transform_sample_counts(physeq, function(x) (x*100) / sum(x) )
print(table(sample_sums(physeq.CSN))) # sanity check total of 100 counts per sample
# Get the mean count per sample for each ASV
cat("\nAverage count of each genus per sample....\n")
meanCountASV <- t(data.frame(as.list(colMeans(otu_table(physeq.CSN)))))
# sum(meanCountASV[,1]) # sanity check should sum to 100
# Get a dataframe with the average count of each Genus per sample
countGenus.df <- meanCountASV %>%
as.data.frame()%>%
rownames_to_column("ASV") %>%
rename(Count=V1) %>%
# Add taxonomy
left_join(as.data.frame(tax_table(physeq.CSN)) %>%
rownames_to_column("ASV"),
by="ASV") %>%
# get a column with Life::Kingdom::Phylum::Class::Order::Family::Genus
mutate(leaf = paste("Life", Kingdom, Phylum, Class, Order, Family, Genus, sep = "::")) %>%
# get average count per sample for each Genus
group_by(leaf, Genus) %>%
summarize(count=sum(Count)) %>% # if several ASVs belong to same Genus, need to sum their counts
# about 30,851 ASVs belong to an unknown genus (which represents ~10% of the counts)
filter(!is.na(Genus))
countGenus.df <- data.frame(count=countGenus.df$count,
row.names = countGenus.df$leaf)
# Return dataframe
return(countGenus.df)
}
#_________________________________
## 3.4. Function to get a dataframe with information on number of datasets where this genus is present ####
dataset_per_genus <- function(physeq){
print("CAUTION: give the agglomerated phyloseq object for shorter running time")
# Get a dataframe with the number of dataset(s) each Genus is found in
datasetGenus.df <- physeq %>%
# melt to long format
psmelt() %>%
# keep only ASVs with a count != 0 in this specific sample
filter(Abundance != 0) %>%
# get a column with Life::Kingdom::Phylum::Class::Order::Family::Genus
mutate(leaf = paste("Life", Kingdom, Phylum, Class, Order, Family, Genus, sep = "::")) %>%
# get the number of datasets with non-0 count for each genus
group_by(leaf, Genus) %>%
summarize(n_dataset = n_distinct(author))
datasetGenus.df <- data.frame(n_dataset=datasetGenus.df$n_dataset,
row.names = datasetGenus.df$leaf)
# Return dataframe
return(datasetGenus.df)
}
# ******************
# 4. PLOT TREES ####
# ******************
path.data <- file.path(path.root, "data/analysis-combined/01_TaxonomicTree")
colors <- paste0(brewer.pal(6, "Dark2"), "99", sep="")
names(colors) <- c("Actinobacteriota", "Bacteroidota", "Firmicutes", "Proteobacteria", "Verrucomicrobiota", "Other")
## *********************
## 4.1. All samples ####
# Agglomerate to Genus level
physeq.glom <- tax_glom(physeq.all, "Genus")
# saveRDS(physeq.glom, file.path(path.data, "physeq_all_glomGenus.rds")) # recommend to save it as takes a while to compute
# physeq.glom <- readRDS(file.path(path.data, "physeq_all_glomGenus.rds"))
# Get the treedata object, and info on nb of ASV per genus, average count of each genus per sample, sample types containing the genus.
tree.all <- phyloseq_to_treedata(physeq=physeq.glom)
asvDF.all <- nb_ASV_per_genus(physeq=physeq.all)
# countDF.all <- count_per_genus(physeq=physeq.all)
datasetDF.all <- dataset_per_genus(physeq=physeq.glom)
sampleType.df <- physeq.glom %>%
# melt to long format
psmelt() %>%
# keep only ASVs with a count != 0
filter(Abundance != 0) %>%
# get a column with Life::Kingdom::Phylum::Class::Order::Family::Genus
mutate(leaf = paste("Life", Kingdom, Phylum, Class, Order, Family, Genus, sep = "::")) %>%
# get the sample_type(s) each genus can be found in
group_by(leaf, Genus) %>%
summarize(spltype = paste(sort(unique(sample_type)), collapse=","))
sampleType.df <- data.frame(spltype=sampleType.df$spltype,
row.names=sampleType.df$leaf)
# Plot tree (all genera)
p1 <- ggtree(tree.all, layout="circular", aes(color=group), lwd=0.4)+
# geom_tiplab(aes(label=new_label), size=2, color="black")+
scale_color_manual(values=colors)+
labs(color="Phylum")
# Add outer layers
p2 <- gheatmap(p1, asvDF.all, offset=0.5, width=.08, colnames=FALSE)+
scale_fill_gradient2(low = muted("red"),
mid = "white",
high = "#2b8cbe",
trans="log",
breaks=c(1,10,100,1000),
name="Number of ASVs")
# p3 <- gheatmap(p2+new_scale_fill(),
# countDF.all, offset=1.1, width=.08, colnames = FALSE)+
# scale_fill_gradient(low = "white",
# high = muted("red"),
# trans="log",
# breaks=c(1e-5,1e-3,1e-1,10),
# labels = parse(text=c("10^-5","10^-3","10^-1", "10")),
# name="Mean relative abundance (%)")+
# labs(title="All samples")
p3 <- gheatmap(p2+new_scale_fill(),
datasetDF.all, offset=1.1, width=.08, colnames = FALSE)+
scale_fill_gradient(low = "#ffffe5",
high = "#ec7014",
breaks = c(1,5,10),
name="Number of datasets")
gheatmap(p3+new_scale_fill(),
sampleType.df, offset=1.7, width=.08, colnames = FALSE)+
scale_fill_manual(values=c("#f0f0f0","#636363","#bdbdbd"), name="Sample type")+
labs(title="All samples")+
scale_y_reverse() # flip tree up/down
ggsave(file.path(path.data, "taxTree_all.jpg"), width=12, height=8)
## ***********************
## 4.2. Fecal samples ####
# Agglomerate to Genus level
physeq.fecal.glom <- tax_glom(physeq.fecal, "Genus")
# saveRDS(physeq.fecal.glom, file.path(path.data, "physeq_fecal_glomGenus.rds")) # recommend to save it as takes a while to compute
# physeq.fecal.glom <- readRDS(file.path(path.data, "physeq_fecal_glomGenus.rds"))
# Get the treedata object, and info on nb of ASV per genus, average count of each genus per sample.
tree.fecal <- phyloseq_to_treedata(physeq=physeq.fecal.glom)
asvDF.fecal <- nb_ASV_per_genus(physeq=physeq.fecal)
countDF.fecal <- count_per_genus(physeq=physeq.fecal)
datasetDF.fecal <- dataset_per_genus(physeq=physeq.fecal.glom)
p1_fecal <- ggtree(tree.fecal, layout="circular", aes(color=group), lwd=0.4)+
scale_color_manual(values=colors)+
labs(color="Phylum")
p2_fecal <- gheatmap(p1_fecal, asvDF.fecal, offset=0.5, width=.08, colnames=FALSE)+
scale_fill_gradient2(low = muted("red"),
mid = "white",
high = "#2b8cbe",
trans="log",
breaks=c(1,10,100,1000),
limits=c(1,4200),
name="Number of ASVs")
p3_fecal <- gheatmap(p2_fecal+new_scale_fill(), countDF.fecal, offset=1.1, width=.08, colnames = FALSE)+
scale_fill_gradient(low = "white",
high = muted("red"),
trans="log",
breaks=c(1e-5,1e-3,1e-1,10),
limits=c(1e-6, 25),
name="Average count per sample (%)")+
labs(title="Fecal samples")
gheatmap(p3_fecal+new_scale_fill(),
datasetDF.fecal, offset=1.7, width=.08, colnames = FALSE)+
scale_fill_gradient(low = "#ffffe5",
high = "#ec7014",
limits=c(1,13),
breaks = c(1,5,10),
name="Number of datasets")+
scale_y_reverse() +# flip tree up/down
labs(title="Fecal samples")
ggsave(file.path(path.data, "taxTree_fecal.jpg"), width=12, height=8)
## *************************
## 4.3. Sigmoid samples ####
# Agglomerate to Genus level
physeq.sigmoid.glom <- tax_glom(physeq.sigmoid, "Genus")
# saveRDS(physeq.sigmoid.glom, file.path(path.data, "physeq_sigmoid_glomGenus.rds")) # recommend to save it as takes a while to compute
# physeq.sigmoid.glom <- readRDS(file.path(path.data, "physeq_sigmoid_glomGenus.rds"))
# Get the treedata object, and info on nb of ASV per genus, average count of each genus per sample.
tree.sigmoid <- phyloseq_to_treedata(physeq=physeq.sigmoid.glom)
asvDF.sigmoid <- nb_ASV_per_genus(physeq=physeq.sigmoid)
countDF.sigmoid <- count_per_genus(physeq=physeq.sigmoid)
datasetDF.sigmoid <- dataset_per_genus(physeq=physeq.sigmoid.glom)
p1_sigmoid <- ggtree(tree.sigmoid, layout="circular", aes(color=group), lwd=0.4)+
scale_color_manual(values=colors)+
labs(color="Phylum")
p2_sigmoid <- gheatmap(p1_sigmoid, asvDF.sigmoid, offset=0.5, width=.08, colnames=FALSE)+
scale_fill_gradient2(low = muted("red"),
mid = "white",
high = "#2b8cbe",
trans="log",
breaks=c(1,10,100,1000),
limits=c(1,4200),
name="Number of ASVs")
p3_sigmoid <- gheatmap(p2_sigmoid+new_scale_fill(), countDF.sigmoid, offset=1.1, width=.08, colnames = FALSE)+
scale_fill_gradient(low = "white",
high = muted("red"),
trans="log",
breaks=c(1e-5,1e-3,1e-1,10),
limits=c(1e-6, 25),
name="Average count per sample (%)")+
labs(title="Sigmoid samples")
gheatmap(p3_sigmoid+new_scale_fill(),
datasetDF.sigmoid, offset=1.7, width=.08, colnames = FALSE)+
scale_fill_gradient(low = "#ffffe5",
high = "#ec7014",
limits=c(1,13),
breaks = c(1,5,10),
name="Number of datasets")+
scale_y_reverse() +
labs(title="Sigmoid samples")
ggsave(file.path(path.data, "taxTree_sigmoid.jpg"), width=12, height=8)