library(ggplot2)
library(stringr)
library(gridExtra)
# W matrix is loaded and its rownames are set to the rownames of the original abundance matrix
# name the columns, ie the ES
es_names <- colnames(W_norm_byES) <- paste("ES", c(1:dim(W_norm_byES)[2]), sep = "_")
# normalize the W matrix by column, to get the relative abundance of genera in ES
W_norm_byES = sweep(W,2,colSums(W),"/")
# work with a data frame
dfw = as.data.frame(100*W_norm_byES)
dfw <-tibble::rownames_to_column(dfw, "tax")
# split the taxa ranks
dfw[c('kingdom', 'phylum', 'class', 'order', 'family', 'genus')] <- str_split_fixed(dfw$tax, ';', 6)
# set up a threshold of 3% for labelling of a genus in an ES
threshold <- 3
# prepare a list of plots
all_ES_plots <- list()
# loop over each ES to create individual barplots
for (es in es_names){
# label the genera only if relative abundance is > 0.03
dfw[[paste0("label", "_", es)]] <- ifelse(dfw[[es]] > threshold, dfw$genus, "")
# set up the max y value
maxy <- max(dfw[[es]])+0.1*max(dfw[[es]])
# main plot
p <- ggplot(dfw, aes_string(x="tax", y=es, fill="phylum")) +
geom_bar(stat="identity") +
labs(x="Genus", fill="Phylum") +
theme_classic() +
ylim(0, maxy) +
theme(panel.grid = element_blank(),
axis.title.x = element_blank(),
axis.line.x = element_blank(),
axis.text.x = element_blank(),
legend.position = "right",
panel.border = element_rect(colour = "black", fill=NA),
axis.text=element_text(size=10),
axis.ticks.x = element_blank(),
legend.text=element_text(size=8),
legend.title=element_text(size=8),
axis.title=element_text(size=10),
strip.text.x=element_text(size=10)
) +
geom_hline(yintercept = threshold, linetype="dashed", color="#DCDCDC") +
geom_text(aes(label = .data[[paste0("label", "_", es)]]), vjust = 0, angle = 15, hjust = 0, size = 2.5)
# enable text to superimpose outside the plot area
gg_table <- ggplot_gtable(ggplot_build(p + ggtitle(gsub("_", "-", es, perl = TRUE)) + labs(y="Relative ES composition (%)")))
gg_table$layout$clip[gg_table$layout$name=="panel"] <- "off"
grid.draw(gg_table)
# add the plot to the list
all_ES_plots[[es]] <- gg_table
}
# in order to visualize the plots, use grid.draw()
grid.draw(all_ES_plots$ES_1)