微生物物种组成和差异物种可视化

概要

样本微生物物种组成和分组样本微生物组成均能反应微生物的物种整体分布情况,再此基础上,一般会对其进行显著性检验,从而区分具体哪一类物种在组间是显著差异。与此同时,也有研究者会对门水平的B和P菌群的比值关注。

导入数据和R包

所需数据已经上传至百度网盘: https://pan.baidu.com/s/1kRBAaECL0xG-SZeeb21BqA 提取码:请邮件 zouhua1@outlook.com

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
# curate data
library(xlsx)
library(tibble)
library(dplyr)

dat <- read.xlsx("taxonomy.xlsx", sheetIndex = 1)
phen <- read.csv("phenotype.csv")
phylum <- dat %>% select(c(2, 8:37)) %>%
group_by(phylum) %>%
summarise_each(sum) %>%
ungroup() %>%
column_to_rownames("phylum")

# configure color
library(ggplot2)
library(pheatmap)
library(scales)
library(varhandle)

grp <- c("Case", "Control")
grp.col <- c("#EE2B2B", "#2D6BB4")
top.col <- c("#6C326C", "#77A2D1", "#FFD169", "#635F5F", "#D4D09A",
"#993116", "#6798CE", "#146666", "#CE9924", "#6D659D",
"#9F9B27", "#6D659D", "#9F9B27", "#C80b8A", "#2C3A89",
"#C8C5C5", "#90E2BF", "#FDAB4D", "#F4F4E8", "#B054BF",
"#FCE873", "#FFCCDB", "#AFD300", "#B089D8", "#F96E6F",
"#AAD3ED", "#639BCE")

R function

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
wilcox_fun <- function(x, y, DNAID, GROUP,
grp1=NULL, grp2=NULL){

# determine x with two cols and names are corret
phe <- x %>% select(c(DNAID, GROUP))
colnames(phe)[which(colnames(phe) == DNAID)] <- "SampleID"
colnames(phe)[which(colnames(phe) == GROUP)] <- "Stage"
if (length(which(colnames(phe)%in%c("SampleID","Stage"))) != 2){
warning("x without 2 cols: DNAID, GROUP")
}

# select groups
if(length(grp1)){
phe.cln <- phe %>% filter(Stage%in%c(grp1, grp2)) %>%
mutate(Stage=factor(Stage, levels = c(grp1, grp2)))
pr <- c(grp1, grp2)
} else{
phe.cln <- phe %>% mutate(Stage=factor(Stage))
pr <- levels(phe.cln$Stage)
}

if (length(levels(phe.cln$Stage)) > 2) {
stop("The levels of `group` are more than 2")
}

# profile
sid <- intersect(phe.cln$SampleID, colnames(y))
prf <- y %>% select(sid) %>%
rownames_to_column("tmp") %>%
filter(apply(select(., -one_of("tmp")), 1,
function(x){sum(x > 0)/length(x)}) > 0.2) %>%
data.frame() %>% column_to_rownames("tmp") %>%
t() %>% data.frame()

# judge no row of profile filter
if (ncol(prf) == 0) {
stop("No row of profile to be choosed\n")
}

# merge phenotype and profile
mdat <- inner_join(phe.cln %>% filter(SampleID%in%sid),
prf %>% rownames_to_column("SampleID"),
by = "SampleID")
dat.phe <- mdat %>% select(c(1:2))
dat.prf <- mdat %>% select(-2)

res <- apply(dat.prf[, -1], 2, function(x, grp){
dat <- as.numeric(x)
p <- signif(wilcox.test(dat ~ grp, paired = F)$p.value, 6)
# median
md <- signif(median(dat), 4)
mdn <- signif(tapply(dat, grp, median), 4)
if ( mdn[1] > mdn[2] & p < 0.05) {
enrich1 <- pr[1]
} else if (mdn[1] < mdn[2] & p < 0.05) {
enrich1 <- pr[2]
} else if (p > 0.05 | mdn[1] == mdn[2]){
enrich1 <- "No significance"
}

# rank
rk <- rank(dat)
rnk <- signif(tapply(rk, grp, mean), 4)
if ( rnk[1] > rnk[2] & p < 0.05) {
enrich2 <- pr[1]
} else if (rnk[1] < rnk[2] & p < 0.05) {
enrich2 <- pr[2]
} else if (p > 0.05 | rnk[1] == rnk[2]){
enrich2 <- "No significance"
}
occ <- signif(tapply(dat, grp, function(x){
round(sum(x > 0)/length(x), 4)}), 4)

res <- c(p,enrich1,enrich2,occ,md,mdn,rnk)
return(res)
}, dat.phe$Stage) %>%
t(.) %>% data.frame(.) %>%
rownames_to_column("type") %>%
varhandle::unfactor(.)

colnames(res)[2:11] <- c("Pvalue", "Enrich_median", "Enrich_rank",
paste0(pr, "_occurence"), "median_all",
paste0(pr, "_median"), paste0(pr, "_rank"))
res$Block <- paste0(pr[1], "_vs_", pr[2])
number <- as.numeric(table(dat.phe$Stage))
res$Num <- paste0(pr[1], number[1], "_vs_",
pr[2], number[2])
res.cln <- res %>% select(c(1,12:13, 2:11)) %>%
mutate(Pvalue=as.numeric(Pvalue)) %>%
mutate(FDR=p.adjust(Pvalue, method = "BH")) %>%
arrange(FDR, Pvalue)
res2 <- res.cln[,c(1:4,14,5:13)]


# scale profile
dat.prf.cln <- prf[, -1]
dat.phe.cln <- dat.phe %>% mutate(Group=ifelse(Stage==pr[1], 0, 1))
idx <- which(colnames(dat.phe.cln) == "Group")

# glm result for odd ratios 95%CI
glmFun <- function(m, n){
dat.glm <- data.frame(group=m, marker=scale(n, center=T, scale=T))
model <- summary(glm(group ~ marker, data = dat.glm,
family = binomial(link = "logit")))
res <- signif(exp(model$coefficients["marker",1]) +
qnorm(c(0.025,0.5,0.975)) * model$coefficients["marker",1], 2)

return(res)
}

glm_res <- t(apply(dat.prf.cln, 2, function(x, group){
res <- glmFun(group, as.numeric(x))
return(res)
}, group = dat.phe.cln[, idx]))
Odd <- glm_res %>% data.frame() %>%
setNames(c("upper", "expected","lower")) %>%
mutate("Odds Ratio (95% CI)" = paste0(expected, " (", lower, ";", upper, ")"))
Odd$type <- rownames(glm_res)

res_merge <- inner_join(res2,
Odd[, c(4:5)], by = "type")

return(res_merge)
}

tax_bar_plot <- function(prf=phylum,
test=phylum_wilcox,
num=20){
# prf=family
# test=family_wilcox
# num <- 20

prf.cln <- prf %>% rownames_to_column("type") %>%
filter(type%in%test$type) %>%
column_to_rownames("type")

mdat <- inner_join(phen %>% select(SampleID, Group),
prf.cln %>% t() %>%
data.frame() %>%
rownames_to_column("SampleID"),
by = "SampleID")
mdat.num.mean <- mdat %>%
select(-c("SampleID", "Group")) %>%
summarise_each(mean) %>%
tidyr::gather(key="tax", value="value") %>%
arrange(desc(value)) %>%
slice(c(1:num)) %>%
mutate(tax=as.character(tax),
tax2=tax)

mdat.num.mean.no <- mdat %>%
select(-c("SampleID", "Group")) %>%
summarise_each(mean) %>%
tidyr::gather(key="tax", value="value") %>%
arrange(desc(value)) %>%
slice(-c(1:num)) %>%
mutate(tax=as.character(tax))

if(nrow(mdat.num.mean.no) == 0){
other.group.mean <- data.frame()
other.individual <- data.frame()
}else{
other.group.mean <- mdat %>%
select(-SampleID) %>%
group_by(Group) %>%
summarise_each(mean) %>%
ungroup() %>%
tidyr::gather(key="tax", value="value", -Group) %>%
filter(tax%in%mdat.num.mean.no$tax) %>%
select(-tax) %>%
group_by(Group) %>%
summarise_each(sum) %>%
mutate(tax="Other")
other.individual <- mdat %>%
select(-Group) %>%
tidyr::gather(key="tax", value="value", -SampleID) %>%
filter(tax%in%mdat.num.mean.no$tax) %>%
mutate(SampleID=factor(SampleID, levels = as.character(phen$SampleID))) %>%
select(-tax) %>%
group_by(SampleID) %>%
summarise_each(sum) %>%
mutate(tax="Other")
}

taxonomy <- c(gsub("\\.", ";", mdat.num.mean$tax), "Other")
mdat.group.mean <- mdat %>%
select(-SampleID) %>%
group_by(Group) %>%
summarise_each(mean) %>%
tidyr::gather(key="tax", value="value", -Group) %>%
filter(tax%in%mdat.num.mean$tax) %>%
mutate(Group=factor(Group, levels = grp)) %>%
mutate(tax=gsub("\\.", ";", tax)) %>%
rbind(other.group.mean) %>%
mutate(tax=factor(tax, levels = taxonomy))

mdat.individual <- mdat %>%
select(-Group) %>%
tidyr::gather(key="tax", value="value", -SampleID) %>%
filter(tax%in%mdat.num.mean$tax) %>%
mutate(SampleID=factor(SampleID, levels = as.character(phen$SampleID))) %>%
mutate(tax=gsub("\\.", ";", tax)) %>%
rbind(other.individual) %>%
mutate(tax=factor(tax, levels = taxonomy))

p_group <- ggplot(mdat.group.mean, aes(x = Group, y = value, fill = tax)) +
geom_bar(stat= 'identity', position = 'fill',width = 0.5)+
#scale_fill_brewer(palette = 'Paired') +
scale_fill_manual(values = top.col) +
scale_y_continuous(labels = percent,
expand = c(0, 0)) +
labs(x = '', y = 'Relative Abundance', fill = NULL)+
guides(fill = guide_legend(ncol = 1, bycol = TRUE, override.aes = list(size = 5))) +
theme_bw()+
theme(axis.title.y = element_text(face = 'bold',color = 'black',size = 14),
axis.title.x = element_text(face = 'bold',color = 'black',size = 14,vjust = -1.2),
axis.text.y = element_text(face = 'bold',color = 'black',size = 10),
axis.text.x = element_text(face = 'bold',color = 'black',size = 12,
angle = 45,vjust = 0.5),
panel.grid = element_blank(),
legend.position = 'right',
legend.key.height = unit(0.6,'cm'),
legend.text = element_text(face = 'bold',color = 'black',size = 10))

p_indi <- ggplot(mdat.individual, aes(x = SampleID, y = value, fill = tax)) +
geom_bar(stat= 'identity', position = 'fill',width = 0.5)+
#scale_fill_brewer(palette = 'Paired') +
scale_fill_manual(values = top.col) +
scale_y_continuous(labels = percent,
expand = c(0, 0)) +
labs(x = '', y = 'Relative Abundance', fill = NULL)+
guides(fill = guide_legend(ncol = 1, bycol = TRUE, override.aes = list(size = 5))) +
theme_bw()+
theme(axis.title.y = element_text(face = 'bold',color = 'black',size = 14),
axis.title.x = element_text(face = 'bold',color = 'black',size = 14,
vjust = -1.2),
axis.text.y = element_text(face = 'bold',color = 'black',size = 10),
axis.text.x = element_text(face = 'bold',color = 'black',size = 12,
angle = 45,vjust = 0.5),
panel.grid = element_blank(),
legend.position = 'right',
legend.key.height = unit(0.6,'cm'),
legend.text = element_text(face = 'bold',color = 'black',size = 10))

require(patchwork)
plot_res <- (p_indi + p_group) +
plot_layout(ncol = 2, widths = c(3, 1),
guides = "collect") & theme(legend.position='right')
return(plot_res)
}

heatFun <- function(prf=phylum,
test=phylum_wilcox,
num=10){

# prf=phylum
# test=phylum_wilcox
# num=10

prf.cln <- prf %>% rownames_to_column("type") %>%
filter(type%in%test$type) %>%
column_to_rownames("type")

mdat <- inner_join(phen %>% select(SampleID, Group),
prf.cln %>% t() %>%
data.frame() %>%
rownames_to_column("SampleID"),
by = "SampleID")
mdat.total.mean <- mdat %>%
select(-c("SampleID", "Group")) %>%
summarise_each(mean) %>%
tidyr::gather(key="tax", value="value") %>%
arrange(desc(value)) %>%
slice(c(1:num)) %>%
mutate(tax=as.character(tax))

rank_name <- paste0( grp, "_rank")

dat <- test %>% select(c("type", "Pvalue", "Enrich_rank", rank_name)) %>%
filter(type%in%unique(mdat.total.mean$tax))
dat_es <- dat %>% select(c("type", rank_name)) %>%
column_to_rownames("type")%>%
setNames(grp) %>%
mutate(Case=as.numeric(Case),
Control=as.numeric(Control))

rownames(dat_es) <- gsub("\\.", ";", dat$type)

dat_note <- dat %>% select(type, Pvalue, Enrich_rank) %>%
mutate(Case=ifelse(Pvalue < 0.05 & Enrich_rank=="Case", "*", ""),
Control=ifelse(Pvalue < 0.05 & Enrich_rank=="Control",
ifelse(Pvalue < 0.01, "**", "*"), "")) %>%
select(type, grp) %>%
mutate(type=gsub("\\.", ";", type)) %>%
column_to_rownames("type")


require(RColorBrewer)
require(pheatmap)
pheatmap(mat = dat_es,
color = colorRampPalette(c("#19499B", "white", "#E5211A"))(100),
scale = "row",
cluster_row = FALSE,
cluster_cols = FALSE,
fontsize = 8,
cellwidth = 20,
cellheight = 20,
show_colnames = T,
border_color = "black",
display_numbers = dat_note,
fontsize_number = 20,
number_color = "white")
}


BP_ratio_fun <- function(x,
tax_tag=c("p__Bacteroidetes", "p__Firmicutes")){

tax_name <- tax_tag
phylum_bp <- x[rownames(x)%in%tax_name, ] %>%
t() %>% data.frame() %>%
rownames_to_column("SampleID") %>%
mutate(FB_ratio=p__Firmicutes/p__Bacteroidetes)

tax_bp_phe <- inner_join(phen %>% select(SampleID, Group),
phylum_bp %>% select(SampleID, FB_ratio),
by = "SampleID") %>%
mutate(Group=factor(Group, levels = grp))
is_outlier <- function(x) {
return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))
}
res <- tax_bp_phe %>% group_by(Group) %>%
mutate(is_outlier=ifelse(is_outlier(FB_ratio), FB_ratio, as.numeric(NA))) %>%
ungroup()


pl <- ggplot(res, aes(x=Group, y=FB_ratio))+
geom_dotplot(binaxis='y', stackdir='center', dotsize = 1)+
stat_summary(aes(fill=Group), fun.data=mean_sdl, fun.args = list(mult=1),
geom="errorbar", width=0.1, size=1) +
stat_summary(fun=median, geom="point", color="red", size=4, shape=17)+
labs(x="", y="F/B ratio")+
scale_y_continuous(breaks = seq(0, 6, 2),
limits = c(0, 7),
expand = c(0, 0))+
scale_fill_manual(values = grp.col)+
guides(fill=F)+
annotate("segment", x = 1, xend = 2, y = 6.4, yend = 6.4, color = "black", size=1)+
annotate("text", x = 1.5, y = 6.7, color = "black", size=6, label = "p=0.011")+
theme_classic()+
theme(axis.title.y = element_text(face = 'bold',color = 'black',size = 14),
axis.title.x = element_text(face = 'bold',color = 'black',size = 14,
vjust = -1.2),
axis.text.y = element_text(face = 'bold',color = 'black',size = 10),
axis.text.x = element_text(face = 'bold',color = 'black',size = 12),
axis.line = element_line(color = "black", size = 1),
panel.grid = element_blank())
return(pl)
}

组合图形

1
2
3
4
5
6
7
8
9
10
11
12
require(ggplotify)
phylum_wilcox <- wilcox_fun(phen, phylum, "SampleID", "Group")
p1 <- tax_bar_plot(prf = phylum, test = phylum_wilcox, num = 20)
p2 <- as.ggplot(heatFun(prf = phylum, test = phylum_wilcox, num = 20))
p3 <- BP_ratio_fun(phylum)

require(patchwork)
p1/(
(p2+p3) +
plot_layout(ncol = 2, widths = c(2, 1))) +
plot_layout(widths = c(1, 1.5)) +
plot_annotation(tag_levels = c('A', '1'))

参考

1.如何拼接pheatmap和ggplot2图形

参考文章如引起任何侵权问题,可以与我联系,谢谢。


------------- The End Thanks for reading --------