How to get skbio PCoA Principal Coordinate Analysis results?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Principal Coordinate Analysis (PCoA), also called Classical Multidimensional Scaling, is a dimensionality reduction technique that takes a distance matrix and produces a set of coordinates in a lower-dimensional space that best preserves the original distances. It is widely used in ecology and bioinformatics to visualize differences between microbial communities, genetic samples, or ecological sites. The scikit-bio (skbio) library provides skbio.stats.ordination.pcoa() to perform PCoA in Python.
Prerequisites
Install scikit-bio and its dependencies:
scikit-bio requires NumPy, SciPy, and pandas. It works on Python 3.8+.
Creating a Distance Matrix
PCoA requires a skbio.DistanceMatrix as input. You can create one from a 2D array or compute it from sample data:
From ecological abundance data using a beta diversity metric:
Running PCoA
Accessing PCoA Results
The OrdinationResults object contains several important attributes:
Coordinates (Sample Scores)
Proportion Explained (Eigenvalues)
Plotting PCoA Results
Color by Group Metadata
Using the Built-in Plot Method
OrdinationResults has a built-in plot() method for quick visualization:
For 3D plots (requires mpl_toolkits):
Statistical Testing with PERMANOVA
After PCoA visualization, test whether groups are statistically different:
Common Pitfalls
- Non-symmetric or negative diagonal:
DistanceMatrixrequires a symmetric matrix with zeros on the diagonal. Even floating-point rounding can causeDistanceMatrix(data)to fail. Use(data + data.T) / 2to force symmetry andnp.fill_diagonal(data, 0)to fix the diagonal. - Negative eigenvalues: Some distance metrics (like UniFrac or custom metrics) can produce distance matrices that are not Euclidean, resulting in negative eigenvalues. PCoA will still run, but the proportion explained may not sum to 1. Use
pcoa(dm, method='fsvd', number_of_dimensions=3)for faster computation that avoids this issue. - Too few samples: PCoA with fewer than 4 samples produces at most 3 axes and may not give meaningful results. Ensure adequate sample size for your study.
- Interpreting distances: PCoA preserves distances, not correlations. Points close together on the plot are similar according to your distance metric. The choice of metric (Bray-Curtis, UniFrac, Euclidean) strongly affects interpretation.
- Missing sample IDs: If your distance matrix IDs do not match your metadata index, coloring by group will fail silently or raise an error. Always verify alignment with
dm.idsandmetadata.index.
Summary
- Use
skbio.stats.ordination.pcoa(distance_matrix)to run PCoA - Access coordinates with
results.samples(DataFrame with PC1, PC2, ..., columns) - Check variance explained with
results.proportion_explained— report this in publications - Create distance matrices with
skbio.diversity.beta_diversity()or from a NumPy array viaDistanceMatrix() - Plot with
results.samplesand matplotlib, or use the built-inresults.plot()method - Follow up with PERMANOVA (
skbio.stats.distance.permanova) to test group significance
Related reading
- How to get SVMs to play nicely with missing data in scikit-learn?
- How to get the count of each distinct value in a column?
- How to get the last N rows of a pandas DataFrame?
- How to get the Stackdriver charts into a csv file?
- How to get string objects instead of Unicode from JSON
- How to get subprocess' stdout data asynchronously?
- How to get the value of a tensor? Python
- How to get the weight vector in Logistic Regression?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.