Taxonomic profiles
A taxonomic profile depends on the assay, the classifier, and its reference database. Amplicon counts measure marker sequences. Kraken2 assigns reads using sequence matches, and Bracken estimates their distribution at a requested rank. Their numbers must retain those definitions when they enter a plot.
This example aggregates the cohort’s reference OTUs to phylum. All counts remain in the denominator, including counts without a resolved phylum. It computes a mean of sample proportions, so a deeply sequenced sample does not dominate the mean solely because it contributed more reads.
Run this example
Section titled “Run this example”The example uses the prepared Kostic colorectal cohort. The workflow and dataset page explains its source, paired design, and selection rule. Counts, taxonomy, and metadata come from the same public archive. The original features are reference OTUs, not ASVs from the separate ampliseq demonstration.
The companion repository
is private and requires access. Its microbiome:0.1.0 container provides the
packages, and the runner mounts the prepared tables at /fixtures.
Run each language’s blocks in order. The container runs without network access.
Read the data and calculate the result
Section titled “Read the data and calculate the result”The taxonomy table is matched by feature identifier before aggregation. The figure shows the eight most abundant phyla and combines the remainder into Other. That display rule changes the legend, not the denominator.
The paired counts and metadata come from Kostic and colleagues, distributed in the pinned phyloseq example archive. McMurdie and Holmes distribute that package under AGPL-3. The source notice records the exact archive, the 76-subject selection, and the applicable package terms.
The read subset comes from SRR12324253, covered by the INSDC data policy. The Langmead laboratory supplies the October 22, 2026 PlusPF index and permits its use and analysis results for any purpose. The source notice records the exact subset, database manifest, and underlying NCBI terms.
library(ggplot2)library(jsonlite)
counts <- read.delim( "/fixtures/cohort_counts.tsv", row.names = 1, check.names = FALSE)counts <- t(as.matrix(counts))metadata <- read.delim("/fixtures/cohort_metadata.tsv")metadata <- metadata[match(rownames(counts), metadata$sample_id), ]stopifnot(identical(rownames(counts), metadata$sample_id))stopifnot(all(counts >= 0), all(counts == floor(counts)))dir.create("outputs", showWarnings = FALSE)
taxonomy <- read.delim("/fixtures/cohort_taxonomy.tsv")taxonomy <- taxonomy[match(colnames(counts), taxonomy$feature_id), ]stopifnot(!anyNA(taxonomy$feature_id))phylum <- sub("^p__", "", taxonomy$phylum)phylum[is.na(phylum) | phylum == ""] <- "Unclassified"aggregated <- t(rowsum(t(counts), group = phylum))relative <- aggregated / rowSums(aggregated)top <- names(sort(colMeans(relative), decreasing = TRUE))[1:8]display <- cbind(relative[, top], Other = rowSums(relative[, !colnames(relative) %in% top, drop = FALSE]))means <- rowsum(display, metadata$tissue) / as.vector(table(metadata$tissue))plot_data <- as.data.frame(as.table(means))names(plot_data) <- c("tissue", "phylum", "proportion")figure <- ggplot(plot_data, aes(tissue, proportion, fill = phylum)) + geom_col(width = 0.65) + theme_minimal(base_size = 12) + labs(x = "Tissue", y = "Mean sample proportion", fill = "Phylum")ggsave("outputs/taxonomic_profiles_r.png", figure, width = 7, height = 4, dpi = 160)cat("Taxonomic groups including unresolved phyla:", ncol(aggregated), "\n")cat(sprintf("Largest mean sample proportion: %.6f\n", max(colMeans(relative))))write_json(list(groups = ncol(aggregated), reads = sum(aggregated), largest_mean = max(colMeans(relative))), "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)Taxonomic groups including unresolved phyla: 17Largest mean sample proportion: 0.442488
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import statsfrom scipy.spatial.distance import pdist, squareform
counts = pd.read_csv( "/fixtures/cohort_counts.tsv", sep="\t", index_col=0).Tmetadata = pd.read_csv( "/fixtures/cohort_metadata.tsv", sep="\t", index_col=0).loc[counts.index]assert counts.index.equals(metadata.index)assert (counts.to_numpy() >= 0).all()assert (counts.to_numpy() == np.floor(counts.to_numpy())).all()output = Path("outputs")output.mkdir(exist_ok=True)
taxonomy = pd.read_csv( "/fixtures/cohort_taxonomy.tsv", sep="\t", index_col=0, dtype=str)taxonomy.index = taxonomy.index.astype(str)counts.columns = counts.columns.astype(str)taxonomy = taxonomy.loc[counts.columns]phylum = taxonomy["phylum"].str.replace("p__", "", regex=False)phylum = phylum.fillna("").replace("", "Unclassified")aggregated = counts.T.groupby(phylum).sum().Trelative = aggregated.div(aggregated.sum(axis=1), axis=0)top = relative.mean().nlargest(8).indexdisplay = relative.loc[:, top].copy()display["Other"] = relative.drop(columns=top).sum(axis=1)means = display.groupby(metadata["tissue"]).mean()axis = means.plot.bar(stacked=True, figsize=(7, 4), rot=0)axis.set(xlabel="Tissue", ylabel="Mean sample proportion")axis.legend(title="Phylum", bbox_to_anchor=(1, 1))figure = axis.figurefigure.tight_layout()figure.savefig(output / "taxonomic_profiles_python.png", dpi=160)plt.close(figure)print(f"Taxonomic groups including unresolved phyla: {aggregated.shape[1]}")print(f"Largest mean sample proportion: {relative.mean().max():.6f}")metrics = {"groups": aggregated.shape[1], "reads": int(aggregated.to_numpy().sum()), "largest_mean": float(relative.mean().max())}(output / "metrics_python.json").write_text(json.dumps(metrics))Taxonomic groups including unresolved phyla: 17Largest mean sample proportion: 0.442488
Read the shotgun reports in R and Python
Section titled “Read the shotgun reports in R and Python”The next example uses reports from the executed taxprofiler demonstration. Its input is the first 100,000 paired records from a public Zymo mock sample. These reports do not describe the colorectal cohort above.
Kraken2 classifies each retained pair as one fragment in this run. Its root clade and unclassified row together define the number of fragments submitted to the classifier. The code reads only those two rows for that denominator and never sums clade counts across ranks.
The Bracken figure divides species estimates by the sum of those estimates. That conditional denominator excludes fragments that Bracken did not allocate to a reported species. The code also exports estimates divided by all classified and unclassified input fragments, so the two scales remain available.
bracken <- read.delim("/fixtures/shotgun_bracken.tsv", check.names = FALSE)kraken <- read.delim("/fixtures/shotgun_kraken_report.tsv", header = FALSE)names(kraken) <- c("percent", "clade", "direct", "rank", "taxid", "name")stopifnot(all(bracken$taxonomy_lvl == "S"))stopifnot(sum(kraken$taxid == 0) == 1, sum(kraken$taxid == 1) == 1)unclassified <- kraken$clade[kraken$taxid == 0]fragments <- unclassified + kraken$clade[kraken$taxid == 1]estimated <- sum(bracken$new_est_reads)bracken$within_estimated <- bracken$new_est_reads / estimatedbracken$of_input <- bracken$new_est_reads / fragmentsstopifnot(estimated <= fragments, all(bracken$new_est_reads >= 0))write.table(bracken, "outputs/shotgun_species_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)top_species <- head(bracken[order(-bracken$new_est_reads), ], 10)top_species$name <- factor( top_species$name, levels = rev(top_species$name))figure <- ggplot(top_species, aes(within_estimated, name)) + geom_col(fill = "#286b8f") + theme_minimal(base_size = 12) + labs(x = "Fraction of Bracken species estimates", y = NULL)ggsave("outputs/shotgun_profiles_r.png", figure, width = 8, height = 5, dpi = 160)cat("Fragments submitted to Kraken2:", fragments, "\n")cat(sprintf("Unclassified fragment fraction: %.6f\n", unclassified / fragments))cat("Reported Bracken species:", nrow(bracken), "\n")cat("Estimated fragments across reported species:", estimated, "\n")metrics <- read_json("outputs/metrics_r.json", simplifyVector = TRUE)metrics$shotgun_fragments <- fragmentsmetrics$shotgun_unclassified <- unclassifiedmetrics$shotgun_species <- nrow(bracken)metrics$shotgun_estimated <- estimatedwrite_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)Fragments submitted to Kraken2: 99996Unclassified fragment fraction: 0.058702Reported Bracken species: 13Estimated fragments across reported species: 93886
bracken = pd.read_csv("/fixtures/shotgun_bracken.tsv", sep="\t")kraken = pd.read_csv( "/fixtures/shotgun_kraken_report.tsv", sep="\t", header=None, names=["percent", "clade", "direct", "rank", "taxid", "name"])assert (bracken["taxonomy_lvl"] == "S").all()assert (kraken["taxid"] == 0).sum() == 1assert (kraken["taxid"] == 1).sum() == 1unclassified = int(kraken.loc[kraken["taxid"] == 0, "clade"].iloc[0])fragments = unclassified + int( kraken.loc[kraken["taxid"] == 1, "clade"].iloc[0])estimated = int(bracken["new_est_reads"].sum())bracken["within_estimated"] = bracken["new_est_reads"] / estimatedbracken["of_input"] = bracken["new_est_reads"] / fragmentsassert estimated <= fragmentsassert (bracken["new_est_reads"] >= 0).all()bracken.to_csv(output / "shotgun_species_python.tsv", sep="\t", index=False)top_species = bracken.nlargest(10, "new_est_reads").iloc[::-1]figure, axis = plt.subplots(figsize=(8, 5))axis.barh(top_species["name"], top_species["within_estimated"], color="#286b8f")axis.set(xlabel="Fraction of Bracken species estimates")figure.tight_layout()figure.savefig(output / "shotgun_profiles_python.png", dpi=160)plt.close(figure)print("Fragments submitted to Kraken2:", fragments)print(f"Unclassified fragment fraction: {unclassified / fragments:.6f}")print("Reported Bracken species:", len(bracken))print("Estimated fragments across reported species:", estimated)metrics.update({"shotgun_fragments": fragments, "shotgun_unclassified": unclassified, "shotgun_species": len(bracken), "shotgun_estimated": estimated})(output / "metrics_python.json").write_text(json.dumps(metrics))Fragments submitted to Kraken2: 99996Unclassified fragment fraction: 0.058702Reported Bracken species: 13Estimated fragments across reported species: 93886
The ten displayed species do not exhaust the report. A small estimate is not proof that the organism belongs to the mock community. Database coverage, shared sequences, and the fixed 150-base Bracken model affect this result. The Bracken manual defines the report fields and the model’s read length parameter.
Read the denominator before the color
Section titled “Read the denominator before the color”A stacked bar hides variation between patients. It also forces every sample to sum to one, so an increase in one component changes the displayed proportions of the others. The plot cannot establish absolute microbial load or a tissue effect.
For shotgun reports, distinguish reads assigned directly to a taxon from reads assigned anywhere below that taxon. Summing a Kraken clade count across every rank counts descendants repeatedly. Select one rank and retain the unclassified fraction separately.
The Kraken2 manual defines these report fields. The Bracken paper explains why abundance reestimation differs from a raw classification count.
Further reading
Section titled “Further reading”-
The manual separates fragments in a taxon clade from fragments assigned directly to it. It also defines the root and unclassified report rows used for the complete input denominator.
-
The documentation describes read reestimation using a database and a specified read length. A species sum remains conditional on the assignments retained by that procedure.