OK, so your solution works well–thanks!
I just exported the data (in this case family-level data) as csv from the barplot in qiime2view and ran your code. I did not realize that the barplot csv file exported from qiime2 in qiime2view would already have the metadata incorporated in the csv file at the very end as the last few columns. This is much easier than trying to combine the metadata and features table manually.
The code:
library(tidyverse)
library(MicrobeR)
library(qiime2R)
data<-
read_csv(“DKP_lv5_Ixodes_barplot_allD_allK.csv”) %>%
select(-BarcodeSequence, -LinkerPrimerSequence, -Species, -Sample_number, -Description) %>% #remove columns which are not helpful
select(SampleID=index, Sex, Region, everything()) #reorder and rename
data[,4:ncol(data)]<-t(apply(data[,4:ncol(data)], 1, function(x) 100*(x/sum(x)))) # convert to percents maintaining metadata in first 3 columns
TopTaxa<-
data.frame(MeanAbundance=colMeans(data[,4:ncol(data)])) %>% #can figure out the 10 most abundant families to plot, and count everything as other
rownames_to_column(“Family”) %>%
top_n(10, MeanAbundance) %>%
pull(Family)
data %>%
gather(-SampleID, -Sex, -Region, key=Taxon, value=Abundance) %>%
mutate(Family=if_else(Taxon %in% TopTaxa, Taxon, “Other”)) %>%
mutate(Family=factor(Family, levels=rev(c(TopTaxa, “Other”)))) %>%
group_by(SampleID, Sex, Region, Family) %>%
summarize(Abundance=sum(Abundance)) %>% #collapse all other taxa to a single category
ggplot(aes(x=SampleID, y=Abundance, fill=Family)) +
geom_bar(stat=“identity”) +
facet_wrap(Region~Sex, scales=“free_x”) + # creates a separate panel for the combinations of sex and region
theme_bw() + # a good built in theme
coord_cartesian(expand=F) + #remove space around the bars
theme(axis.text.x=element_text(angle=45, hjust=1)) + #rotate x axis text
theme(legend.text = element_text(size=5)) + # family names to fit
scale_fill_manual(
values=rev(c(
"blue4",
"olivedrab",
"firebrick",
"gold",
"darkorchid",
"steelblue2",
"chartreuse1",
"aquamarine",
"yellow3",
"coral",
"grey"))
) #these are the default microber colors but you can change as you see fit or use an automatic color scheme like scale_fill_viridis_d()
ggsave(“barplots.pdf”, width=10, height=7.5)
Looks very nice, thank you.