forked from microsud/microbiomeutilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot_taxa_boxplot.R
81 lines (60 loc) · 2.56 KB
/
plot_taxa_boxplot.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
#' @title Taxonomic Composition Plot boxplot
#' @description Plot taxon abundance for samples.
#' @param x \code{\link{phyloseq-class}} object
#' @param taxonomic.level Merge the OTUs (for phyloseq object) into a higher taxonomic level. This has to be one from colnames(tax_table(x)).
#' @param top.otu Top number of taxa to plot.
#' @param VariableA Specify main variable of interest. This should be one of the variables in sample_variables(x).
#' @param title title for the plot
#' @param color any of the palette supported by ggpubr/RColorBrewer packages or user specified as c("red", "blue").
#' @return A \code{\link{ggplot}} plot object.
#' @export
#' @examples \dontrun{
#' # Example data
#' library(microbiomeutilities)
#' library(RColorBrewer)
#' data("zackular2014")
#' ps1 <- zackular2014
#' pn <- plot_taxa_boxplot(ps1,
#' taxonomic.level = "Phylum",
#' top.otu = 3, VariableA = "DiseaseState",
#' title = "Rel plot", color = "Set2")
#' print(pn)
#' }
#'
#' @keywords utilities
plot_taxa_boxplot <- function(x, taxonomic.level, top.otu, VariableA, title, color = NULL){
Abundance <- NULL
if (!is.null(x@phy_tree)){
message("For plotting purpuses the phy_tree will be removed")
x@phy_tree = NULL
}
else {
message("The phy_tree slot is empty, easy to make the plot")
}
taxic <- as.data.frame(x@tax_table);
# using abundances function from microbiome as sometime otu_table can have taxa_are_rows FALSE in phyloseq
otudf <- as.data.frame(abundances(x));
taxic$OTU <- row.names(otudf);
taxmat <- as.matrix(taxic);
new.tax <- tax_table(taxmat);
tax_table(x) <- new.tax;
# Merge the taxa at a higher taxonomic level
if (!taxonomic.level == "OTU") {
x <- aggregate_top_taxa(x, taxonomic.level, top = top.otu)
}
x1 <- transform(x, "compositional")
x.df0 <- suppressWarnings(suppressMessages(phy_to_ldf(x1, transform.counts = NULL)))
p <- ggplot(x.df0, aes(x =x.df0[,taxonomic.level],
y=Abundance,
fill = x.df0[,VariableA]))
p <- p + geom_boxplot(position = position_dodge(1)) +
geom_point(position = position_dodge(width = 0.75),
aes(group = x.df0[, VariableA]))
p <- p + ggtitle(title) + theme_bw() +
theme(axis.text.x = element_text(face ="italic",
angle = 90))
p <- p + ylab("Relative abundance") + xlab(taxonomic.level) +
scale_fill_brewer(VariableA,
palette = color)
return(p)
}