R code that produced this figure
plot_beta_diversity(beta_demo, label_name = "SampleOrigin", ellipses = TRUE)Microbiota diversity and immunoglobulin-coating analysis from 16S sequencing
You do not have to read it front to back. It is built so you can enter anywhere:
Every figure here was produced by running the same code the app runs, on the example datasets that ship with it. If you follow along, your screen will look like these pages.
The app also documents itself in three places, and this tutorial does not duplicate them: the ⓘ icon next to a control explains that control; the About this analysis panel at the top of each analysis tab explains the method; the Choice of parameters tab in Beta Diversity is a full reference on ordination pipelines. When something here is deliberately brief, that is where the detail lives.
Plenty of tools compute alpha and beta diversity. PhyloIgSeq does that too, but it was built around six things that are harder to find elsewhere.
It scores antibody coating, not just composition. IgSeq (IgA-seq and relatives) sorts a microbiome sample into antibody-coated (Ig+) and uncoated (Ig−) fractions and sequences each. Comparing the two tells you which bacteria the host immune system is targeting — a different question from “who is there”. The app computes the established indices (Palm, Kau, probability-based) plus a sliding Z-score developed for this package.
It judges each taxon against its own kind. A rare taxon and a dominant taxon do not have the same natural variability, so scoring both against one dataset-wide expectation systematically favours one of them. The sliding Z-score re-estimates what “no coating” looks like inside a window that slides along the abundance axis, so every taxon is compared with taxa of similar abundance.
It can measure the noise instead of assuming it. If you sequenced two aliquots of the negative fraction, neither is coated, so any difference between them is pure experimental noise. The app uses that as the reference the real Ig+ vs Ig− signal has to beat. Most methods assume a theoretical null instead.
It stays fast on large tables (sparsity). Abundance tables are mostly zeros. The underlying package keeps the table in a sparse format and computes Bray-Curtis, Jaccard and UniFrac distances directly on it, without ever expanding it to a full dense matrix. In the app you see this as a Sparse-optimized / Unoptimized grouping in the distance-metric menu: the first group scales, the second can be slow and memory-hungry on a big dataset.
It handles genuinely missing values (incompleteness). An Ig-score table is not a sparse abundance table: when a taxon was not observed in a sample there simply is no score, and writing 0 would mean “not coated”, which is a different and false claim. The app keeps those entries missing and fits a low-rank model to place samples relative to one another — so you can ordinate coating profiles without inventing data.
It records what you did. Every export includes a parameters sheet listing the filters, transforms and scoring settings that produced it, so a result can be reproduced months later. Plots can additionally be exported as .rds objects you can reopen and restyle in R.
There is a seventh thing that is easy to miss: the Exploration tab turns everything the app has computed — diversity values, ordination axes, individual taxon abundances, Ig scores — into ordinary variables you can plot and test against each other and against your sample metadata. See Section 12.
Input. One phyloseq object saved as an .rds file, typically the output of a DADA2 pipeline:
saveRDS(my_phyloseq_object, "my_data.rds")It must contain an abundance (OTU/ASV) table, a taxonomy table and sample metadata. Uploads are capped at 50 MB. A phylogenetic tree is optional — see Section 8.
Extra requirements for IgSeq. Two sample-metadata columns: one saying which sorted fraction each row is (Ig+, Ig−, …), and one saying which rows came from the same biological sample.
Practise data. Three datasets ship with the app, available under Import → Data source → Use an example dataset. Nothing you do to them can break anything, so click everything.
| Dataset | Size | What it is | Use it for |
|---|---|---|---|
ps_16s_refinement |
515 taxa × 37 samples, has a tree | Comparison of 16S protocols: two human donors, two mock communities, one negative control | Everything except IgSeq |
ps_igseq |
4703 taxa × 38 samples, no tree | Mouse IgA-seq toy set: 8 biological samples across pos, neg1, neg2, whole fractions |
The IgSeq pipeline |
ps_phage_display |
400 taxa × 32 samples | Phage-display panning: one shared input library and three selection rounds | Multiple positive fractions |
Useful ps_16s_refinement variables, since the rest of this document uses them: SampleOrigin (HD1, HD2, MCS Genomic, MCS Whole Cell, NegCTRL), PCR (Nested, Standard), Platform (BioFidal, GenoToul), LogConcentration (numeric).
In ps_igseq, only sorting_fraction and sample_id are real; sex, age, batch, operator and ig_pheno are synthetic filler — do not interpret them.
If you’re coming from the wet-lab side rather than sequencing analysis, a few words in this app are used more narrowly than they might suggest elsewhere. Ten seconds now saves confusion later.
| Term | What it means here |
|---|---|
| Sample | One physical thing you sequenced — one swab, one stool aliquot, one sorted fraction. One row of the metadata table. |
| Taxon (plural taxa) | One row of the abundance table: one distinct sequence that got counted. Not necessarily a named species — see below. |
| ASV (Amplicon Sequence Variant) | One exact DNA sequence, kept distinct down to a single nucleotide — the modern default output of pipelines like DADA2. |
| OTU (Operational Taxonomic Unit) | The older convention: near-identical sequences (commonly ≥97% similar) clustered into one unit before counting. |
| Taxonomic rank | A level of classification — Kingdom, Phylum, Class, Order, Family, Genus, Species — assigned to a taxon by comparing its sequence to a reference database. |
The distinction that trips people up: a taxon is not the same thing as a taxonomic rank. A rank is a level, the way “city” is a level of a postal address. A taxon is one specific row, the way one specific street address is one thing. So when this app — or its plots, or its “taxon” columns — says “taxon”, read it as one row of the abundance table, which before you agglomerate is one ASV or OTU. That is a statement about what got counted, not a claim that it has been identified as a distinct species: plenty of ASVs are classified only down to Family or Genus, and some not at all.
Agglomerate means merging every taxon that shares the same value at a chosen rank into one row — “Agglomerate to Genus” sums every ASV assigned to Bacteroides into a single Bacteroides row. This is what Agglomerate to a taxrank controls throughout the app (Alpha Diversity, Beta Diversity, Heatmap, IgSeq): fewer, coarser rows, easier to read, at the cost of resolution below that rank. Taxa left unclassified at the chosen rank are agglomerated together into one “unassigned” bucket — worth a quick check that it isn’t a large share of your data before trusting a genus-level plot.
The taxonomy table itself — Kingdom through Species, one column per rank — is on the Import tab’s Taxonomy sub-tab.
The app has a lot of controls. Four conventions cover nearly all of it.
1. The Submit line splits every sidebar. Controls above the Submit button change what gets computed, and nothing happens until you press Submit. Controls below it are display options that apply the instant you change them. This is why a sidebar can look unresponsive: you were above the line. It is also why exploring is cheap once a result exists — recolouring, regrouping and faceting cost nothing.
2. Help comes in two layers. The ⓘ icon beside a control explains that control. The About this analysis panel at the top of each analysis tab explains what the analysis is and how to read its output. Both are always there; neither is repeated in full here.
3. Save fills an export basket. Nearly every plot and table has a small Save checkbox. Ticking it does not download anything — it marks that output for inclusion in the ZIP you build later on the Export Results tab. Tick as you go.
4. Only the first two tabs are obligatory. Import, then Filter. After that, Tree, Alpha Diversity, Beta Diversity, Heatmap, Exploration and IgSeq are independent — take what your question needs, in any order. The › arrow beside Submit walks you along the default order if you want one.
| Your question | Go to | The controls that matter |
|---|---|---|
| Did my sequencing work? Any failed samples? | Import → Abundance | Rarefaction curves, reads per sample |
| Which samples and taxa should I trust? | Filter | The three filter blocks; abundance thresholds |
| I need a variable that doesn’t exist yet (e.g. genotype × timepoint) | Filter → Derived Variables | Combine / recode |
| How diverse is each individual sample? | Alpha Diversity | Measure; grouping variable; Check depth |
| Are my groups’ communities different overall? | Beta Diversity | Transform, distance, method; PERMANOVA |
| How much variance does this specific variable explain? | Beta Diversity | Supervised model: predictors + confounders |
| Which taxa drive the difference? | Heatmap | Sort taxa by → variation or effect size |
| Does X relate to Y (anything to anything)? | Exploration → Univariate | Y, X, confounders |
| Which features separate two groups, screening many at once? | Exploration → Volcano | Binary Y; FDR |
| Which taxa does the host antibody target? | IgSeq | Fractions; zero treatment; Sliding Z |
| Do coating profiles cluster by group? | IgSeq, then Beta Diversity | Use Ig scores instead of abundances |
| I need UniFrac but have no tree | Tree | Build from taxonomy |
| How do I get all this out? | Export Results | Save checkboxes; Select all |
Fifteen minutes end to end, on ps_16s_refinement. Every later section expands on a step here.
SampleOrigin · NegCTRL. The negative control is a technical sample and would distort every comparison. Submit.SampleOrigin and tick Show statistics. Now switch it to LogConcentration and watch the boxplot become a scatter without resubmitting. Tick Check depth.SampleOrigin and tick Ellipses.SampleOrigin, Top annotations → SampleOrigin. Submit.Alpha: Shannon, X → Sample: LogConcentration, Build Plot.plot_beta_diversity(beta_demo, label_name = "SampleOrigin", ellipses = TRUE)These two tabs are the only obligatory ones. Everything downstream works from the object they produce.
Upload an .rds, or pick an example dataset. Three options are worth understanding.
Make new (more readable) taxa names. Real ASV identifiers are often entire DNA sequences, which make every plot unreadable. This replaces them with ASV_1, ASV_2, … and saves the old-to-new correspondence as a table you can export, so nothing is lost.
Make taxa names unique at each rank. Taxonomies frequently reuse a name across lineages, or leave ranks unassigned. This disambiguates them so that agglomerating at, say, Genus does not silently merge two different genera.
Rarefaction curves. Slow on large objects, which is why it is optional, but it answers a question you want answered early: would deeper sequencing have found more taxa? A curve that flattens says you sequenced deep enough; one still climbing steeply says you did not.
# show_legend = FALSE: a per-sample legend just lists 36 sample names and
# crowds out the plot; which curve belongs to which sample rarely matters here.
plot_rarefaction(ps_demo, show_legend = FALSE)After Submit, four sub-tabs appear. Metadata is the important one to read: every “group by”, “colour by” and “test against” offered anywhere else in the app comes from this table. Abundance is where you spot samples that failed to sequence.
Three independent filter blocks, applied in order, plus rarefaction.
Filter samples and Filter taxa work the same way: click Add Filter to add a row, choose Include or Exclude, pick a variable, then pick values (categorical) or a range (numeric). Extra rows combine with AND / OR. Sample filters act on metadata, taxa filters on the taxonomy table.
Filter by abundance removes shallow samples and rare taxa by read count. Open the Abundance sub-tab in the main panel before dragging the sliders — you can then see the threshold move against the actual distribution instead of guessing.
plot_reads(ps_demo, min_sample_sum = 1000, min_taxa_sum = 5)Easy to overlook, and often the fastest route to the analysis you actually want. If the variable you need does not exist — genotype crossed with timepoint, or a yes/no flag for a set of values, or four groups collapsed into two — build it here. It then behaves like any other metadata column everywhere in the app: group by it, colour by it, test against it.
The SampleType variable used later in Section 12.2 (Mock vs Donor, from four SampleOrigin levels) is exactly this kind of derived variable.
Rarefying means randomly subsampling every sample down to the same read depth, so depth differences cannot masquerade as biology. It works, and it throws away real data to do it. The literature genuinely disagrees, and the app links both sides rather than pretending otherwise.
Two things are worth knowing beyond that debate:
Rarefaction is off by default.
Enable IgSeq pipeline sits at the top of this sidebar. Tick it, name the metadata column that records the sorted fraction, and say which fraction values the ordinary diversity analyses should use (typically the unsorted or pre-sort fraction). Submit, and the IgSeq tab unlocks. See Part III.
A short, optional service tab.
The tree relates taxa to one another. Its main job is that UniFrac distances in Beta Diversity require one — no tree, no UniFrac.
It has two possible sources. If your phyloseq object came with a real alignment-based phylogenetic tree, it is used. If not, you can build one from the taxonomy table here, using taxonomic ranks as levels (Hierarchy is the recommended method).
plot_phylo_tree(ps_genus_tree, tip_color = "Phylum")A taxonomy-derived tree is a heuristic. Its branch lengths are not evolutionary distances. It is fine as a weighting scheme for UniFrac; it is not a phylogeny and must not be used for phylogenetic inference.
The question: how diverse is one sample, on its own?
Alpha diversity is a single number per sample, combining how many taxa are present (richness) and how evenly they are spread (evenness).
| Measure | What it rewards | Needs raw counts |
|---|---|---|
| Shannon | Both richness and evenness. \(H = -\sum p_i \ln p_i\) — larger when there are more taxa and when no single taxon dominates | no |
| Observed | Pure richness: how many distinct taxa were seen, ignoring abundance | no |
| Simpson / InvSimpson | Dominance: driven mostly by the few most abundant taxa | no |
| Chao1 / ACE / Fisher | Richness including an estimate of taxa you missed | yes |
Above the line, choose the measure and optionally a rank to agglomerate to first. Submit. Below the line, choose the grouping variable — and note that the app picks the plot type from the variable’s type: a categorical variable gives you a boxplot with an optional test, a numeric one gives you a scatter with a correlation. You do not resubmit for this.
plot_alpha_diversity(alpha_demo, x = "SampleOrigin", stat = TRUE)Alpha diversity depends heavily on sequencing depth: sequence a sample deeper and you will find more taxa. If the group that looks “more diverse” is also the group you sequenced deeper, you have measured your sequencer, not your biology.
Tick Check depth — it scales each point by its read count — before believing any result on this tab. The richness estimators (Observed, Chao1, ACE, Fisher) are the most exposed, and no abundance transform can repair them; rarefaction is the only real remedy.
plot_alpha_diversity(alpha_demo, x = "LogConcentration", check_depth = TRUE)The question: how different are samples from each other?
Alpha diversity gave one number per sample. Beta diversity compares samples to each other: compute a dissimilarity for every pair, then project those distances down to two axes you can look at. Each point is an entire community; points close together have similar composition.
Three choices interact — the transform, the distance and the ordination method — and the combinations are not all valid. The Choice of parameters tab inside Beta Diversity is the full reference. This is the short version:
| Transform | Distance | Unsupervised | Supervised |
|---|---|---|---|
| CLR or Hellinger | (euclidean) | PCA, PCoA, NMDS, t-SNE, UMAP | RDA, dbRDA |
| Proportions or raw counts | bray | PCoA, NMDS, t-SNE, UMAP | dbRDA |
| Proportions or counts | UniFrac (needs a tree) | PCoA, NMDS | dbRDA |
| Raw counts only | — | CA, DCA | CCA |
Proportions + Bray-Curtis + PCoA is the standard, safe default in microbial ecology, and is what Figure 1 uses. A few rules behind the table:
The axis labels give the percentage of variation each axis captures. Set Label to a categorical variable to colour by it, and tick Ellipses (above the plot, next to Save) to draw a confidence region per group.
PERMANOVA tests whether the groups really differ. Tick Compute permutation p-value; the R² it reports is the fraction of total variation explained by the grouping, and the p-value says whether that is more than chance would give. The variable being tested is whichever one you set as Label.
scree_plot(beta_demo$eigen_values)PERMANOVA compares group centres, but it is also sensitive to group spread. If one group is much more variable than another, you can get a significant result even when the centres coincide. Look at the ellipses: if one is far wider than the other, do not read a significant p-value as “the groups sit in different places”.
Everything above is unsupervised: the axes summarise the largest variation, whatever causes it. Tick Supervised (constrained) model and it inverts — the app builds axes that specifically explain variables you name.
Two boxes, and the distinction between them is the entire point:
Putting PCR in Predictors and Platform in Confounders asks: once sequencing platform is accounted for, does PCR protocol still explain community composition?
NA elsewhere, with a warning.The question: fine, the groups differ — but which taxa are driving it?
Beta diversity tells you that communities differ. It does not tell you what differs. This does. Each cell is one taxon in one sample, coloured by abundance; the dendrograms reorder rows and columns so similar profiles sit together.
The one control worth understanding on this tab is Sort taxa by. By default the app shows you the most variable/abundant taxa — the big players, which are often the same in every group and therefore uninformative. Switch it to variation or effect size and pick a variable, and the rows become the taxa that most strongly differ across that variable (Kruskal-Wallis effect size for a categorical variable, absolute Spearman correlation for a numeric one). The twenty rows on screen become the twenty taxa that actually separate your groups.
Top annotations draw your metadata as coloured bars above the columns, which lets you see whether the sample dendrogram recovers your groups without having been told about them.
The heatmap is interactive: drag-select any block of cells to open a zoomed sub-heatmap with readable taxon names.
ComplexHeatmap::draw(
plot_phylo_heatmap(
heatmap_demo,
top_annotation_vars = c("SampleOrigin", "PCR"),
nb_top_taxa = 20,
sort_taxa_by_diff_abundance = TRUE,
var_for_diff_abundance = "SampleOrigin"
),
merge_legend = TRUE
)Both dendrograms are computed from the transformed table using the distance you chose. Different transform, different clusters. Try two before you believe one. Proportions is the default here for a reason: on raw counts, a heatmap across samples of unequal depth shows depth as much as biology — and the clustering inherits that artefact.
The question: does anything I have computed relate to anything else?
This is the tab most people miss, and the one that ties the app together. Open the X and Y dropdowns and look at what is in them: sample metadata and your derived variables, yes — but also Alpha: diversity values, Beta: ordination axes, every individual taxon’s abundance, and every Ig score if you ran the IgSeq pipeline. Anything the app has computed becomes a variable you can test against anything else. (Start typing to search; the list only shows a few matches at a time.)
Pick a Y and an X and click Build Plot. You do not choose a plot type or a statistical test — the app reads the data types and picks both:
| X and Y | Plot | Test |
|---|---|---|
| numeric ~ numeric | scatter with trend | Pearson correlation |
| numeric ~ categorical | boxplot or violin | t-test (2 groups) or ANOVA (3+) |
| categorical ~ categorical | stacked proportional bars | chi-square |
| categorical ~ numeric | multinomial logistic curve | likelihood-ratio test |
Adding Confounders switches the reported test to a model that adjusts for them. The plot keeps showing the raw, unadjusted relationship — so if the plot and the statistics disagree, that gap is the confounder’s contribution.
explore(
x = sample_df$LogConcentration,
y = alpha_demo$diversity$Shannon[
match(sample_df$sample_id, alpha_demo$diversity$sample_id)
],
x.name = "LogConcentration",
y.name = "Shannon",
color.col = "SampleOrigin"
)$plotVolcano mode inverts the question: instead of one X against one Y, it tests every candidate feature against one binary outcome at once, and summarises all of them in one plot. Effect size runs across, statistical significance runs up. The uninteresting majority sit low and near zero; anything worth following up goes up and out to one side.
local({
vd <- merge(
sample_df[, c("sample_id", "SampleType")],
data.frame(
sample_id = rownames(genus_abundance),
genus_abundance,
check.names = FALSE
),
by = "sample_id"
)
res <- getVolcanoData(
y.name = "SampleType",
data = vd,
id.variable = "sample_id",
positive.name = "Mock",
force.t.test = TRUE,
compute.log2fc = TRUE
)
getVolcanoPlot(res, show.fdr = TRUE, max.overlaps = 8)
})Y must be a two-level variable — build one on the Filter tab if you do not have one. Feature types lets you restrict what gets tested.
You are running hundreds of tests at once, so some will look significant by luck alone. Leave Adjust p-values (FDR) on — it is on by default — and read the FDR axis rather than raw p-values.
One subtlety: effect sizes are only directly comparable between points measured the same way. Mixing feature types can put two different effect-size metrics on one axis, in which case horizontal distance is indicative rather than exact. The axis title always names the metric in use.
Everything so far works on any 16S dataset. This part needs a specific experimental design — if you do not have sorted fractions, you can skip to Section 15.
The host coats some of its gut bacteria with antibody (usually IgA) and not others. An IgSeq experiment sorts one sample by that coating into an Ig+ (coated) and an Ig− (uncoated) fraction, and sequences each separately. A taxon that is much more abundant in Ig+ than in Ig− is being targeted by the immune system; one that is depleted is being ignored. A coating score turns that comparison into a number, per taxon, per sample.
Enable the pipeline on the Filter tab (Section 7.2.3), then configure it on the IgSeq tab, which has three collapsible panels:
Fractions — which value of your fraction column means coated (Ig+), which means uncoated (Ig−), and optionally a second Ig− fraction and a pre-sort fraction.
Two aliquots of the same uncoated material are both, by construction, uncoated. Any difference between them is therefore pure experimental noise — sorting, amplification, sequencing. The app uses that as an empirical null: the real Ig+ vs Ig− signal has to stand out from the noise your own experiment actually produced, rather than from a theoretical distribution someone assumed. It is the single cheapest thing you can do to make these scores trustworthy.
Samples — which column says that several rows came from the same animal or subject.
Parameters — agglomeration rank, the sliding-Z window size, and zero treatment.
A taxon with zero reads in one fraction breaks every ratio — you cannot divide by zero, and you cannot take its logarithm. How you patch that changes your answers, sometimes a lot, so this is a decision rather than a default.
| Strategy | What it does |
|---|---|
| no zero | Drops any taxon that has a zero in either fraction. Honest, but discards the most extreme candidates — a taxon absent from Ig− is exactly the sort of thing you were looking for |
| pseudo count | Adds half the smallest observed count to everything. Simple and predictable; the recommended starting point |
| random pseudo count | Like the above, but drawn randomly rather than fixed |
| bayesian inference | Estimates replacement values from the data’s own composition. The most principled and the slowest |
Set Test zero treatments first to test on one sample (MA plot only), then Submit. The app runs one sample and returns just the MA plot, faceted by strategy, in seconds. Compare, choose, then switch to do all analyses and commit. Do not skip this — it is the difference between choosing a method and stumbling into one.
wrap_subtitle(plot_ma(ma_demo), width = 95)| Score | In one sentence | Needs |
|---|---|---|
| Palm index | The plain Ig+/Ig− abundance ratio | Ig+, Ig− |
| Kau index | The same ratio, normalised by log-abundance | Ig+, Ig− |
| Probability index / ratio | A Bayesian estimate of the chance a given taxon’s cells are coated | Ig+ and either Ig− or a pre-sort fraction plus an Ig+ frequency |
| Purity-corrected variants | The above, un-mixing the fact that neither sorted fraction is pure | Per-fraction Ig+ frequencies. Experimental |
| Sliding Z (recommended) | How extreme this taxon’s shift is, compared with taxa of similar abundance | Ig+, Ig−; better with a second Ig− |
The classical indices assume one expectation for the whole dataset. Sliding Z does not, and that is the difference worth caring about: the spread expected under “no coating” is re-estimated inside a window that slides along the abundance axis, so a rare taxon is judged against rare taxa and an abundant one against abundant taxa. This removes the abundance-dependent bias a raw ratio suffers from.
Most of these scores are either novel to this package or drawn from a scattered literature that rarely spells out the formula in one place. If you want to know exactly what’s under each name, or you’re deciding which one to trust for a specific analysis, the boxes below open with the formula and the score’s specific known limitations. Skip them freely — the table above and the score comparison figure are enough to use the app.
Palm index is the plain ratio of the two fraction abundances:
\[\text{Palm} = \frac{\text{Ig+ abundance}}{\text{Ig− abundance}}\]
Kau index is the same log-ratio, divided by a measure of how abundant the taxon is overall:
\[\text{Kau} = \frac{-\log_2(\text{Ig+}/\text{Ig−})}{\log_{10}(\text{Ig+} \times \text{Ig−})}\]
What that division does in practice: for a taxon seen in only a handful of reads, the denominator is small and the ratio gets scaled down hard, so a wild swing measured on very little evidence counts for less. For an abundant taxon seen in thousands of reads, the denominator is larger and the score sits closer to the raw log-ratio. Kau, in other words, discounts a big swing you’re unsure about more than a big swing you’re confident in — a cruder version of what Sliding Z does with actual windowed spread.
Limitation shared by both: they compare every taxon against one fixed idea of “no coating”, rare and abundant taxa alike — precisely the assumption Sliding Z was built to drop (Section 13.6). Prefer Sliding Z unless you specifically need Palm/Kau for comparison with older literature.
Both estimate P(this taxon’s cells are Ig-coated) via Bayes’ rule. Write \(P\) for the pre-sort Ig+ frequency — the overall share of the whole sample that is coated, on average.
Probability index, using a pre-sort fraction:
\[\text{prob\_index} = \frac{\text{Ig+ abundance} \times P}{\text{pre-sort abundance}}\]
Probability ratio, the log-odds version, using the Ig− fraction instead:
\[\text{prob\_ratio} = \log_2\!\left(\frac{\text{Ig+ abundance} \times P}{\text{Ig− abundance} \times (1-P)}\right)\]
prob_index has a specific, documented problem. Dividing by the pre-sort fraction only behaves as intended when that pre-sort sample is the same material, handled the same way, as the sorted fractions. In practice it often is not — e.g. sequenced without the debris-removal step that precedes sorting — making it a measurably different community. The package’s own testing found prob_index disagreeing with every other score (Spearman ~0.60, against 0.94–1.00 between any other pair) and even exceeding a value of 1 — which a probability cannot do — for about a fifth of taxa, for exactly this reason. It is kept for comparability with older literature; prefer prob_ratio or the purity-corrected pair (Section 13.5) as your primary score.
No sort is perfect. Some cells that should have landed in the Ig− tube leak into Ig+, and vice versa — so neither measured fraction is quite the clean population you wanted to compare. Purity-corrected scores use two extra measurements — how pure each sorted fraction actually came out, typically from flow cytometry — to work out algebraically what the comparison would have looked like with perfectly clean fractions.
purity_correction_schematic()Call \(p\) the fraction of the Ig+ tube that is truly coated (its purity) and \(q\) the fraction of the Ig− tube that is truly coated (its impurity — ideally close to 0). Given \(p\), \(q\), and how much of each taxon showed up in each tube, there is exactly one way to work out how much of that taxon would have been in a perfectly pure coated tube and a perfectly pure uncoated tube — that reconstruction is the “un-mixing”, and it’s what pos_ig_freq/neg_ig_freq (set in the IgSeq tab’s Fractions panel) feed into.
Both fractions are a mixture of the same two populations — call them \(a\) (really-coated) and \(b\) (really-uncoated) — in different proportions:
\[\text{Ig+}_t = p\,a_t + (1-p)\,b_t \qquad \text{Ig−}_t = q\,a_t + (1-q)\,b_t\]
for each taxon \(t\). Two equations, two unknowns, solved exactly:
\[a_t = \frac{(1-q)\,\text{Ig+}_t - (1-p)\,\text{Ig−}_t}{p - q} \qquad b_t = \frac{p\,\text{Ig−}_t - q\,\text{Ig+}_t}{p - q}\]
A probability score follows from Bayes’ rule using these recovered populations instead of the raw ones; the ratio score is its logit.
Where it can fail. The algebra assumes coated cells are captured into the Ig+ tube at the same efficiency regardless of taxon. When that’s not quite true — or simply from sampling noise — solving the equations can return a negative population for some taxa, which is meaningless (there is no such thing as -3% of a population). This is common, not rare: a median of 41.5% of taxa per sample fell outside the mathematically valid range in the package’s own test cohort. Affected taxa are clamped to the nearest valid value and nudged by a small regularization term so their score is finite rather than undefined — but for those taxa, the reported value is a floor set by the model, not a direct measurement. The Warnings tab reports how many taxa this affected in your run; a large share usually means the two fractions’ purities are too close together for the correction to resolve anything.
Practical takeaway. Purity correction is worth doing when you have the per-fraction purity measurements, but treat it as experimental — newer and less battle-tested than the plain scores — and always check that Warnings figure before trusting the absolute values. Rankings among taxa hold up better than the numbers themselves.
plot_slide_z(pis, sample_ids = "sample_1")Four things to know before you read one of these:
The grey cloud is your noise floor. It is the same taxa compared between the two negative aliquots. Neither is coated, so its scatter is what your experiment produces from nothing. Red points inside that cloud are not evidence.
Points parked in a block on the far left had a zero. Their abundance is a product of the zero treatment, not a measurement, so they are drawn off to the side rather than at a fabricated position. Read their height (the shift and its Z score); ignore their horizontal position.
Hollow points, on the purity-corrected axis, were clamped. The un-mixing could not place them inside the model’s admissible range, so their value comes from the prior rather than from data. Treat the magnitude as a floor, not a measurement. Their ranking against each other still carries information; a |Z| threshold applied to them does not. The Warnings tab reports how many taxa this affected — a large share usually means the two fractions’ Ig+ frequencies are too close for the correction to resolve anything.
|Z| > 1.96 is a shortlist, not a result. It corresponds roughly to p < 0.05 under a normal null, but taxa within a sample are not independent and no multiple-testing correction is applied. Treat flagged taxa as candidates to follow up.
slide_window_schematic(ma_coords_demo, n_windows = 3)The idea the figure is illustrating: taxa are ranked by abundance and processed in windows, and each window’s own taxa set the spread the taxa inside that window are judged against. A rare taxon is compared with other rare taxa; an abundant one with other abundant ones — which is exactly what removes the abundance-dependent bias a single dataset-wide null would introduce.
For a taxon in a given window, the score is an ordinary Z-score:
\[Z = \frac{\text{obs\_change} - \text{center}}{\text{scale}}\]
where center and scale are estimated from the window’s own taxa, not the whole sample. By default, scale comes from the Ig−.1 vs Ig−.2 comparison — real replicate noise, when a second negative fraction was supplied — and center is that same distribution’s mean, which anchors the score so that 0 means “coated at the same rate as the sample overall”, not merely “typical for this window”.
Depth matters for that anchor. If the Ig+ and Ig− fractions were sequenced to very different depths, the anchor drifts unless each fraction’s own library size is corrected for — which the app does automatically. Under simulation, an uncorrected score at a 10:1 depth imbalance flagged 97% of taxa as “significant” under a null where nothing was actually coated; corrected, that figure was 2%. Nothing to configure here, but it is why keeping your fractions at comparable depth still matters, even though Sliding Z — unlike alpha diversity — needs no rarefaction.
A fixed |Z| > 1.96 threshold means different things depending on your setup. With a second negative fraction (the empirical-null mode this app uses by default), Z is a real signal-to-noise ratio and the threshold is an absolute statement. Without one, the app falls back to scaling each window by its own observed spread, which makes Z self-normalising by construction — roughly the same share of taxa clears the threshold whether the real coating signal is strong or weak. Treat that fallback as a way to rank taxa within a sample, not as a significance test.
Every time. It reports missing values, samples too small to score, taxa the model had to clamp, and samples dropped because their fractions could not be interpreted (duplicated fraction rows, fewer than two fractions, a fraction with no reads). It is the tab that tells you which parts of the pretty plots not to trust.
This tab agglomerates a score by taxonomic rank and by sample group so you can compare groups rather than individual taxa, as a boxplot or a bubble plot.
plot_ig_score(
pis,
plot_type = "boxplot",
score_name = "slide_z",
taxrank_score = "Phylum"
)Start agglomerating score for each controls the order of the two collapsing steps (taxa within a sample first, or samples within a taxon first). The order matters when groups are unbalanced.
If you measured Ig+ frequencies per fraction, the app can report how cleanly each sample sorted, and offer to weight by it (Score agglomeration weight → by sort quality).
The reason is counterintuitive enough to state plainly. Purity correction does not make cleaner sorts count for more. Un-mixing inverts the sort’s compression of the Ig+/Ig− contrast, and it applies that same amplification to noise as to signal. It puts a poor sort back on the right scale while inflating its noise. So in a plain unweighted average, the worst-separated samples carry the widest scores and quietly dominate the result.
This applies when averaging across samples, and only to the purity-corrected probability scores. Averaging across taxa within one sample is unaffected (every taxon there shares the same sort). purity_corrected_slide_z is also unaffected, because a sliding Z divides by its own window’s spread and the inflation cancels.
The app warns you only when it actually matters: a score that is exposed, agglomerated across samples, in a cohort whose sorts really do differ.
knitr::kable(head(sort_quality(pis_long), 4), digits = 3, row.names = FALSE)| sample_id | pos_ig_freq | neg_ig_freq | separation | separation_logit | rel_weight |
|---|---|---|---|---|---|
| sample_1 | 0.8 | 0.1 | 0.7 | 3.584 | 1 |
| sample_2 | 0.8 | 0.1 | 0.7 | 3.584 | 1 |
| sample_3 | 0.8 | 0.1 | 0.7 | 3.584 | 1 |
| sample_4 | 0.8 | 0.1 | 0.7 | 3.584 | 1 |
separation is the gap between the Ig+ frequency in the positive and negative fractions — how cleanly the sort worked. rel_weight is the weight that gap implies. In this toy dataset every sample was given the same frequencies, so all weights are equal; in a real cohort they vary several-fold.
Positive fraction only. If you only sequenced a positive fraction, you can still get prob_index from the positive fraction, a pre-sort fraction and an Ig+ frequency measurement. Every other score is fundamentally a positive-versus-negative comparison and is dropped, with a warning.
Multiple positive fractions, one shared reference. Ig+ fraction(s) is not limited to one value. Set several, and each is compared against the same negative/reference fraction in turn. This is not specific to antibody coating — it is the general shape of “several rounds of selection, each compared back to one shared unselected pool” — so the same pipeline adapts directly to phage-display panning and similar affinity-selection workflows: point Ig+ fraction(s) at each round of selection and Ig− fraction at the shared master (naive) library everything was selected from, and the app scores each round’s enrichment against it exactly as it would score Ig+ against Ig− in an antibody-coating experiment.
ps_phage_display demonstrates this: 8 panning campaigns, each with one shared input (naive) library and three successive output rounds (round1, round2, round3), progressively enriched for a handful of campaign-specific clones. Set Ig+ fraction(s) to round1, round2, round3 and Ig− fraction to input, and every round is scored against the same starting library. Rows are keyed by <sample_id>_<positive fraction>, and gain original_sample_id/positive_fraction_name columns recording which round each came from — usable directly as a facet or colour variable afterwards, so “did enrichment increase from round 1 to round 3” becomes a two-click Exploration question (Section 12). The negative/reference fraction is rarefied once, jointly across every positive fraction of a sample, so every round is compared against it at one common depth rather than each being rarefied separately against a moving target.
(This dataset’s taxonomy table has a single rank, because its rows are phage clones, not bacterial taxa — a reminder that “taxon” just means “one row of the abundance table”, see Section 3.)
The scores are not a dead end. Use Ig scores instead of abundances appears on Alpha Diversity, Beta Diversity and Exploration. Tick it and every analysis in this tutorial works on antibody coating instead of composition — coating diversity per sample, clustering of coating profiles, coating scores as variables to correlate against metadata.
One technical point matters here. An Ig-score table is mostly missing, not mostly zero: if a taxon was not observed in a sample there is no score for it, and writing 0 would assert “measured, and not coated”. So for beta diversity the app keeps those entries missing and fits a low-rank model (an SVD) that places samples relative to each other using only what was actually measured. You can export the resulting sample and taxon coordinates, and the fit itself, from the Export Results tab.
The Save checkbox next to every plot and table is the whole export mechanism: ticking it adds that output to the basket. The Export Results tab then has three sections.
1. Data tables — abundances at the ranks you choose, metadata, taxonomy, ordination coordinates, Ig scores.
2. Plots and other outputs — everything you ticked Save on. Select all grabs the lot; the live summary lists what will actually be included (an item ticked but never computed is skipped rather than silently failing).
3. Export — choose CSV or XLSX for tables, and an image format for plots, then Export & download ZIP.
Two options are worth knowing:
tables/, plots/, objects/.The parameters sheet. Every export includes a parameters table recording the settings that produced it: taxa-renaming choices, the fraction column, every sample and taxa filter expression, your derived-variable definitions, abundance thresholds, whether you rarefied, the tree source and method, and the IgSeq configuration. This is what makes a run reproducible six months later.
It deliberately records only settings that change numbers. Purely graphical choices — colours, point sizes, facets, labels — are not listed, because they are visible in the plot itself and would bury the parameters that actually matter.
One line each; each points back to the section that explains it.
The app is a front end to the PhyloIgSeq R package. If you need something the interface does not offer — a batch of 200 datasets, a custom figure, a step in a pipeline — the same analyses are available directly.
| In the app | In R |
|---|---|
| Filter → abundance thresholds | filter_reads(), plot_reads() |
| Import → rarefaction curves | plot_rarefaction(), rarefy_abundances() |
| Tree → build from taxonomy | get_taxonomy_tree() |
| Alpha Diversity | get_alpha_diversity(), plot_alpha_diversity() |
| Beta Diversity | get_beta_diversity(), plot_beta_diversity(), stat_beta_diversity(), scree_plot() |
| Heatmap | get_phylo_heatmap(), plot_phylo_heatmap() |
| IgSeq → the whole pipeline | getPhyloIgSeq() |
| IgSeq → Sliding Z | compute_slide_z(), plot_slide_z() |
| IgSeq → test mode MA plot | group_sorted_samples(), get_ma_plot_data(), plot_ma() |
| IgSeq → Score Comparison | plot_ig_score(), agglomPhyloIgSeq(), sort_quality() |
| Use Ig scores instead of abundances | PhyloIgSeq_to_phyloseq() |
| Sparse-optimized distances | as_sparse_phyloseq(), sparse_distance(), sparse_unifrac() |
Both package vignettes are worth an hour:
vignette("diversity-analysis", package = "PhyloIgSeq")
vignette("igseq-scoring", package = "PhyloIgSeq")| Term | Meaning |
|---|---|
| ASV / OTU | A distinct sequence variant — the app’s unit of “a taxon” before agglomeration |
| Agglomerate | Merge taxa that share a rank (e.g. all species of one genus) into one row |
| Alpha diversity | How diverse one sample is, on its own |
| Beta diversity | How different two samples are from each other |
| Ordination | Squeezing all the pairwise differences down to two axes you can plot |
| PERMANOVA | A test for whether groups of samples differ in composition |
| R² | The share of total variation a variable explains |
| FDR | An adjusted p-value that accounts for having run many tests at once |
| Confounder | A variable that could explain your result instead of the one you care about |
| Rarefaction | Randomly subsampling all samples to equal read depth |
| Transform | Rescaling abundances (e.g. to proportions) before analysis |
| Sparse | A table that is mostly zeros — stored compactly, so it stays fast |
| Ig+ / Ig− | The antibody-coated and uncoated fractions of a sorted sample |
| Coating score | How strongly host antibodies target a given taxon |
| Null distribution | What the numbers would look like if nothing were going on |
| MA plot | Change between two conditions (vertical) against average abundance (horizontal) |
| Zero treatment | How a zero count in one fraction is handled so ratios stay computable |
| Purity correction | Adjusting for the fact that neither sorted fraction is 100% pure |