[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EG2J858VBFSCGVFF9M8VK2":3,"skill-same:01M7EG2J858VBFSCGVFF9M8VK2":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":31,"commitSha":32,"skillDirectory":33,"forksCount":14,"repositoryHtmlUrl":34,"repositoryHomepageUrl":34,"ownerHtmlUrl":35,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":36,"install":37,"resources":49},"01M7EG2J858VBFSCGVFF9M8VK2","bio-tcr-bcr-analysis-repertoire-visualization",null,"Draws TCR\u002FBCR repertoire figures - V-J chord\u002Fcircos, CDR3 spectratype, clonal-space stratification, clonal tracking across timepoints, rarefaction\u002Fextrapolation curves, overlap heatmaps, and clonotype-similarity networks - and encodes how to read them. Use when choosing between a raw Shannon bar and a rarefaction curve for a diversity comparison; deciding a depth-robust overlap metric (Morisita-Horn) vs a set metric (Jaccard) for a heatmap; setting the distance threshold that defines a clonotype-similarity network; interpreting a Gaussian vs skewed spectratype as polyclonal vs clonally expanded; or laying out clonal-space and clone-tracking plots. Covers VDJtools PlotFancyVJUsage\u002FRarefactionPlot, R circlize and iNEXT, and matplotlib\u002Fseaborn recipes.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-repertoire-visualization\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-tcr-bcr-analysis-repertoire-visualization\ndescription: Draws TCR\u002FBCR repertoire figures - V-J chord\u002Fcircos, CDR3 spectratype, clonal-space stratification, clonal tracking across timepoints, rarefaction\u002Fextrapolation curves, overlap heatmaps, and clonotype-similarity networks - and encodes how to read them. Use when choosing between a raw Shannon bar and a rarefaction curve for a diversity comparison; deciding a depth-robust overlap metric (Morisita-Horn) vs a set metric (Jaccard) for a heatmap; setting the distance threshold that defines a clonotype-similarity network; interpreting a Gaussian vs skewed spectratype as polyclonal vs clonally expanded; or laying out clonal-space and clone-tracking plots. Covers VDJtools PlotFancyVJUsage\u002FRarefactionPlot, R circlize and iNEXT, and matplotlib\u002Fseaborn recipes.\ntool_type: mixed\nprimary_tool: VDJtools\ngoal_approach_exempt: true\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"tcr-bcr-analysis\u002Frepertoire-visualization\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: matplotlib 3.8+, seaborn 0.13+, pandas 2.2+, numpy 1.26+; R circlize 0.4+, iNEXT 3.0+; VDJtools 1.2.1+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nNote: matplotlib 3.9 removed `plt.cm.get_cmap(name, N)`; use `plt.get_cmap(name)` and sample it, or `matplotlib.colormaps[name].resampled(N)`. seaborn 0.13 deprecated bare `palette=` without `hue=`; assign `hue=` and `legend=False`.\n\n# Repertoire Visualization\n\n**\"Plot my TCR\u002FBCR repertoire\"** -> Render V-J usage, CDR3-length spectratype, clonal-space, clonal tracking, diversity\u002Frarefaction, overlap, and similarity-network figures, and read each one correctly.\n- CLI: `vdjtools PlotFancyVJUsage`, `vdjtools RarefactionPlot` (delegates plotting to R)\n- R: `circlize::chordDiagram` (V-J), `iNEXT::iNEXT` + `ggiNEXT` (rarefaction\u002Fextrapolation)\n- Python: `matplotlib`\u002F`seaborn` for bespoke figures; `numpy` multinomial resampling for rarefaction; `networkx` + `rapidfuzz` for similarity networks\n\n## The governing principle: every figure inherits two upstream choices\n\nA repertoire figure is only as valid as the numbers behind it, and those numbers depend on two decisions made before any plot is drawn:\n\n1. The clonotype definition. A clonotype = CDR3 (nucleotide OR amino acid) + optionally V and J. Amino-acid CDR3 collapses convergent recombination (many nt rearrangements -> one aa clonotype), inflating apparent sharing and deflating richness; nt CDR3 is more conservative (Venturi et al. 2006 *PNAS* 103:18691). Every count on every axis shifts with this choice, so it must be stated in the figure and held constant across all samples in a comparison.\n2. The sequencing depth. Richness, Shannon, clonality, and set-overlap (Jaccard, shared-clonotype counts) are strictly increasing functions of reads sequenced - the rare-clone tail never saturates. Diversity, rarefaction, and overlap figures are comparable across samples ONLY after depth normalization: downsample all samples to a common depth, or read rarefaction curves at a shared x. Comparing raw values across libraries of unequal depth measures sequencing effort, not biology (Chao et al. 2014 *Ecol Monogr* 84:45; Greiff et al. 2015 *Genome Med* 7:49). This caveat governs the diversity, rarefaction, and overlap recipes below.\n\n## Choosing the figure and reading it\n\n| Figure | What it reveals | How to compare correctly |\n|--------|-----------------|--------------------------|\n| V-J chord\u002Fcircos | Combinatorial V-J pairing bias within one sample | Descriptive per sample; never compare raw usage across primer sets\u002Fplatforms (primer bias masquerades as biology) |\n| CDR3 spectratype | Clonal structure: Gaussian length distribution = polyclonal\u002Fnaive, spikes = expansion | Weight by frequency to see expansions; by unique clonotypes to see underlying diversity |\n| Clonal-space \u002F proportion | Fraction of repertoire held by rare vs expanded clones | Bin by clone frequency (strata), not raw count; robust to depth if frequency-based |\n| Clonal tracking | Expansion\u002Fcontraction\u002Fpersistence of clones over time | Downsample timepoints to common depth first; an \"absent\" clone is often a sampling zero |\n| Rarefaction\u002Fextrapolation | Diversity comparison done right (interpolate to common depth) | Read all curves at a shared x; extrapolate at most 2-3x observed depth |\n| Overlap heatmap | Pairwise repertoire similarity | Use Morisita-Horn (depth-robust) on depth-normalized samples; Jaccard is depth-biased |\n| Similarity network | Clusters of related CDR3s (candidate specificity groups) | Structure depends entirely on the distance threshold; state it and test sensitivity |\n\n## V-J usage: chord\u002Fcircos and heatmap\n\nThe chord\u002Fcircos shows which V and J segments pair, weighted by clonotype count, within one sample.\n\nVDJtools route (delegates plotting to R; requires `RInstall` once):\n\n```bash\nvdjtools PlotFancyVJUsage -m metadata.txt output_dir\u002F\n```\n\nR with circlize - a V-by-J count matrix becomes a chord diagram:\n\n```r\nlibrary(circlize)\n\nplot_vj_chord \u003C- function(clone_df) {\n    vj_matrix \u003C- table(clone_df$v_gene, clone_df$j_gene)\n    chordDiagram(vj_matrix, transparency = 0.5, annotationTrack = c('grid', 'name'))\n}\n```\n\nPython heatmap alternative (samples x V gene, or V x J for one sample) avoids a chord dependency and reads more quantitatively for many segments:\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef plot_vj_heatmap(clone_df):\n    vj = clone_df.pivot_table(index='v_gene', columns='j_gene', values='frequency', aggfunc='sum', fill_value=0)\n    fig, ax = plt.subplots(figsize=(8, 6))\n    sns.heatmap(vj, cmap='viridis', ax=ax)\n    ax.set_title('V-J pairing frequency')\n    return fig\n```\n\n## CDR3 spectratype: length distribution reveals clonal structure\n\nThe spectratype is a histogram of CDR3 length. A roughly Gaussian, bell-shaped distribution indicates a diverse, polyclonal (naive-like) repertoire; skew or discrete spikes at particular lengths indicate clonal expansion(s). The classic immunoscope spectratype (and VDJtools `CalcSpectratype`) bins nucleotide length, where in-frame clones sit 3 nt apart and the periodicity is part of the readout; amino-acid length is a common simplification - state which is plotted. Weighting by read\u002FUMI frequency shows expansions; weighting by unique clonotypes shows the underlying diversity - the two views can look opposite, so label which is plotted.\n\n```python\ndef plot_spectratype(clone_df, length_col='cdr3_length'):\n    fig, ax = plt.subplots(figsize=(9, 5))\n    bins = range(clone_df[length_col].min(), clone_df[length_col].max() + 2)\n    ax.hist(clone_df[length_col], bins=bins, weights=clone_df['frequency'], color='steelblue')\n    ax.set_xlabel('CDR3 length (aa)')\n    ax.set_ylabel('Frequency')  # Gaussian = polyclonal; spikes = clonal expansion\n    return fig\n```\n\n## Clonal-space \u002F proportion: how much repertoire the big clones hold\n\nBin clones into frequency strata (Rare \u002F Small \u002F Medium \u002F Large \u002F Hyperexpanded) and stack their summed frequency. Because strata are defined on frequency, this view is comparatively depth-robust and shows clonal-space homeostasis at a glance. A treemap of top clones is an alternative when individual dominant clones matter.\n\n```python\nimport numpy as np\n\ndef plot_clonal_space(clone_df, sample_col='sample'):\n    # Frequency-based strata (immunarch homeo convention); frequency makes this depth-robust\n    edges = [0, 1e-4, 1e-3, 1e-2, 1e-1, 1.0]\n    labels = ['Rare', 'Small', 'Medium', 'Large', 'Hyperexpanded']\n    clone_df = clone_df.copy()\n    clone_df['stratum'] = pd.cut(clone_df['frequency'], bins=edges, labels=labels)\n    space = clone_df.groupby([sample_col, 'stratum'], observed=True)['frequency'].sum().unstack(fill_value=0)\n    fig, ax = plt.subplots(figsize=(8, 5))\n    space[labels].plot(kind='bar', stacked=True, ax=ax, colormap='viridis')\n    ax.set_ylabel('Fraction of repertoire')\n    return fig\n```\n\n## Clonal tracking across timepoints\n\nTrack individual clone frequencies over an ordered sample set (vaccination, infection, therapy). A line plot of the top clones, or an alluvial\u002Fstream for the same data, shows expansion, contraction, and persistence. Downsample timepoints to a common depth before declaring contraction - a clone scored absent at one timepoint is frequently below the sampling floor, not truly gone.\n\n```python\ndef plot_clone_tracking(clone_df, top_n=10, clone_col='cdr3_aa', time_col='timepoint'):\n    top = clone_df.groupby(clone_col)['frequency'].sum().nlargest(top_n).index\n    fig, ax = plt.subplots(figsize=(9, 5))\n    for clone in top:\n        d = clone_df[clone_df[clone_col] == clone].sort_values(time_col)\n        ax.plot(d[time_col], d['frequency'], marker='o', label=clone[:12])\n    ax.set_xlabel('Timepoint'); ax.set_ylabel('Clone frequency')\n    ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', fontsize=7)\n    return fig\n```\n\n## Rarefaction\u002Fextrapolation: the correct way to compare diversity\n\nA bare bar of Shannon (or observed richness) across samples of unequal depth is misleading - it plots depth as much as biology. The defensible comparison is a rarefaction\u002Fextrapolation curve: interpolate each sample down to (and extrapolate modestly above) a shared depth, then read diversity at a common x. iNEXT computes this for Hill numbers q=0\u002F1\u002F2 with confidence intervals (Hsieh et al. 2016 *Methods Ecol Evol* 7:1451; Chao et al. 2014 *Ecol Monogr* 84:45).\n\nR route (gold standard, gives CIs):\n\n```r\nlibrary(iNEXT)\n\n# count_list: named list of per-sample integer clonotype-count vectors\nout \u003C- iNEXT(count_list, q = c(0, 1, 2), datatype = 'abundance')\nggiNEXT(out, type = 1)  # diversity vs sample size, read at a common x\n```\n\nVDJtools route: `vdjtools RarefactionPlot -m metadata.txt output_dir\u002F`.\n\nPython resampling route (interpolation by multinomial subsampling) when iNEXT is unavailable:\n\n```python\ndef rarefaction_curve(counts, depths, reps=20, rng=None):\n    # Interpolate observed richness by drawing 'm' reads without-replacement-like via multinomial\n    rng = rng or np.random.default_rng(0)\n    counts = np.asarray(counts, dtype=float)\n    p = counts \u002F counts.sum()\n    total = int(counts.sum())\n    richness = []\n    for m in depths:\n        if m > total:  # interpolation only; do not extrapolate past observed depth here\n            richness.append(np.nan); continue\n        obs = [np.count_nonzero(rng.multinomial(m, p)) for _ in range(reps)]\n        richness.append(np.mean(obs))\n    return richness\n```\n\n## Overlap heatmap: pick a depth-robust metric\n\nAn N-by-N similarity heatmap summarizes pairwise repertoire overlap. The metric choice is the decision: Morisita-Horn is abundance-weighted and near-invariant to sample size, so it is the default across unequal depths; Jaccard (presence\u002Fabsence) is dominated by the shallower sample's depth and should not be compared across unequal-depth pairs. Compute the matrix in vdjtools-analysis on depth-normalized samples, then render it here. Label the metric in the title.\n\n```python\ndef plot_overlap_heatmap(overlap_matrix, metric='Morisita-Horn'):\n    fig, ax = plt.subplots(figsize=(7, 6))\n    sns.heatmap(overlap_matrix, annot=True, fmt='.2f', cmap='YlOrRd', vmin=0, vmax=1, square=True, ax=ax)\n    ax.set_title(f'Repertoire overlap ({metric})')  # state the metric; Jaccard is depth-biased\n    return fig\n```\n\n## Clonotype-similarity network\n\nNodes are CDR3s, edges connect sequences within a chosen distance, and clusters are candidate specificity groups. The network structure depends entirely on the threshold: too loose chains distinct clones together, too tight fragments real groups. State the threshold and metric, and test sensitivity before interpreting clusters. Same-length CDR3s with Hamming distance is the conservative default; Levenshtein allows indels.\n\n```python\nimport networkx as nx\nfrom rapidfuzz.distance import Levenshtein\n\ndef build_similarity_network(clone_df, max_norm_dist=0.15, clone_col='cdr3_aa'):\n    # normalized_similarity in [0,1]; edge when 1 - similarity \u003C= threshold. Structure is threshold-dependent.\n    clones = clone_df[clone_col].unique()\n    g = nx.Graph()\n    g.add_nodes_from(clones)\n    for i, a in enumerate(clones):\n        for b in clones[i + 1:]:\n            if 1 - Levenshtein.normalized_similarity(a, b) \u003C= max_norm_dist:\n                g.add_edge(a, b)\n    return g\n```\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Diversity \"differs\" between groups but tracks library size | Bare Shannon\u002Frichness bar across unequal depth | Downsample to common depth or plot rarefaction curves read at a shared x (iNEXT\u002FRarefactionPlot) |\n| Overlap heatmap shows huge differences driven by one shallow sample | Jaccard\u002Fshared-count on raw, unequal-depth counts | Use Morisita-Horn on depth-normalized samples; label the metric |\n| Network clusters change completely on re-run with a new cutoff | Arbitrary distance threshold; single-linkage chaining | Fix and report the metric + threshold; run a sensitivity sweep; prefer Hamming on same-length CDR3s |\n| Two figures disagree on sharing\u002Fdiversity | Built on different clonotype definitions (nt vs aa, +\u002F- V\u002FJ) | Hold one clonotype definition constant across all figures in a comparison and state it |\n| Spectratype \"expansion\" vanishes when re-plotted | Switched between frequency-weighted and clonotype-weighted histogram | Choose one weighting per figure and label it (frequency shows expansions) |\n| V-usage differences between batches look biological | Multiplex-PCR primer bias | Compare usage only within one protocol, or use UMI\u002F5'RACE data |\n| `plt.cm.get_cmap(name, N)` raises AttributeError | Removed in matplotlib 3.9+ | Use `plt.get_cmap(name)` or `matplotlib.colormaps[name].resampled(N)` |\n\n## Related Skills\n\n- vdjtools-analysis - Compute the diversity\u002Foverlap inputs (depth-normalized)\n- mixcr-analysis - Produce clonotype tables\n- scirpy-analysis - Single-cell clonal-expansion overlays\n- data-visualization\u002Fggplot2-fundamentals - General ggplot2 grammar\n- data-visualization\u002Fheatmaps-clustering - Overlap\u002Fusage heatmap techniques\n\n## References\n\n- Shugay M, et al. VDJtools: unifying post-analysis of T cell receptor repertoires. *PLoS Comput Biol* 2015; 11(11):e1004503. (PlotFancyVJUsage, RarefactionPlot, overlap metrics.)\n- Chao A, Gotelli NJ, Hsieh TC, Sander EL, Ma KH, Colwell RK, Ellison AM. Rarefaction and extrapolation with Hill numbers. *Ecol Monogr* 2014; 84(1):45-67. (Interpolation\u002Fextrapolation framework.)\n- Hsieh TC, Ma KH, Chao A. iNEXT: an R package for rarefaction and extrapolation of species diversity (Hill numbers). *Methods Ecol Evol* 2016; 7(12):1451-1456. (Rarefaction\u002Fextrapolation curves with CIs.)\n- Greiff V, et al. A bioinformatic framework for immune repertoire diversity profiling. *Genome Med* 2015; 7:49. (Hill-number diversity profiling of repertoires.)\n- Venturi V, et al. Sharing of T cell receptors in antigen-specific responses is driven by convergent recombination. *PNAS* 2006; 103(49):18691-18696. (aa-clonotype sharing inflated by convergence.)\n- Chao A. Nonparametric estimation of the number of classes in a population. *Scand J Stat* 1984; 11:265-270. (Chao1 richness estimator.)\n","## Version Compatibility\n\nReference examples tested with: matplotlib 3.8+, seaborn 0.13+, pandas 2.2+, numpy 1.26+; R circlize 0.4+, iNEXT 3.0+; VDJtools 1.2.1+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nNote: matplotlib 3.9 removed `plt.cm.get_cmap(name, N)`; use `plt.get_cmap(name)` and sample it, or `matplotlib.colormaps[name].resampled(N)`. seaborn 0.13 deprecated bare `palette=` without `hue=`; assign `hue=` and `legend=False`.\n\n# Repertoire Visualization\n\n**\"Plot my TCR\u002FBCR repertoire\"** -> Render V-J usage, CDR3-length spectratype, clonal-space, clonal tracking, diversity\u002Frarefaction, overlap, and similarity-network figures, and read each one correctly.\n- CLI: `vdjtools PlotFancyVJUsage`, `vdjtools RarefactionPlot` (delegates plotting to R)\n- R: `circlize::chordDiagram` (V-J), `iNEXT::iNEXT` + `ggiNEXT` (rarefaction\u002Fextrapolation)\n- Python: `matplotlib`\u002F`seaborn` for bespoke figures; `numpy` multinomial resampling for rarefaction; `networkx` + `rapidfuzz` for similarity networks\n\n## The governing principle: every figure inherits two upstream choices\n\nA repertoire figure is only as valid as the numbers behind it, and those numbers depend on two decisions made before any plot is drawn:\n\n1. The clonotype definition. A clonotype = CDR3 (nucleotide OR amino acid) + optionally V and J. Amino-acid CDR3 collapses convergent recombination (many nt rearrangements -> one aa clonotype), inflating apparent sharing and deflating richness; nt CDR3 is more conservative (Venturi et al. 2006 *PNAS* 103:18691). Every count on every axis shifts with this choice, so it must be stated in the figure and held constant across all samples in a comparison.\n2. The sequencing depth. Richness, Shannon, clonality, and set-overlap (Jaccard, shared-clonotype counts) are strictly increasing functions of reads sequenced - the rare-clone tail never saturates. Diversity, rarefaction, and overlap figures are comparable across samples ONLY after depth normalization: downsample all samples to a common depth, or read rarefaction curves at a shared x. Comparing raw values across libraries of unequal depth measures sequencing effort, not biology (Chao et al. 2014 *Ecol Monogr* 84:45; Greiff et al. 2015 *Genome Med* 7:49). This caveat governs the diversity, rarefaction, and overlap recipes below.\n\n## Choosing the figure and reading it\n\n| Figure | What it reveals | How to compare correctly |\n|--------|-----------------|--------------------------|\n| V-J chord\u002Fcircos | Combinatorial V-J pairing bias within one sample | Descriptive per sample; never compare raw usage across primer sets\u002Fplatforms (primer bias masquerades as biology) |\n| CDR3 spectratype | Clonal structure: Gaussian length distribution = polyclonal\u002Fnaive, spikes = expansion | Weight by frequency to see expansions; by unique clonotypes to see underlying diversity |\n| Clonal-space \u002F proportion | Fraction of repertoire held by rare vs expanded clones | Bin by clone frequency (strata), not raw count; robust to depth if frequency-based |\n| Clonal tracking | Expansion\u002Fcontraction\u002Fpersistence of clones over time | Downsample timepoints to common depth first; an \"absent\" clone is often a sampling zero |\n| Rarefaction\u002Fextrapolation | Diversity comparison done right (interpolate to common depth) | Read all curves at a shared x; extrapolate at most 2-3x observed depth |\n| Overlap heatmap | Pairwise repertoire similarity | Use Morisita-Horn (depth-robust) on depth-normalized samples; Jaccard is depth-biased |\n| Similarity network | Clusters of related CDR3s (candidate specificity groups) | Structure depends entirely on the distance threshold; state it and test sensitivity |\n\n## V-J usage: chord\u002Fcircos and heatmap\n\nThe chord\u002Fcircos shows which V and J segments pair, weighted by clonotype count, within one sample.\n\nVDJtools route (delegates plotting to R; requires `RInstall` once):\n\n```bash\nvdjtools PlotFancyVJUsage -m metadata.txt output_dir\u002F\n```\n\nR with circlize - a V-by-J count matrix becomes a chord diagram:\n\n```r\nlibrary(circlize)\n\nplot_vj_chord \u003C- function(clone_df) {\n    vj_matrix \u003C- table(clone_df$v_gene, clone_df$j_gene)\n    chordDiagram(vj_matrix, transparency = 0.5, annotationTrack = c('grid', 'name'))\n}\n```\n\nPython heatmap alternative (samples x V gene, or V x J for one sample) avoids a chord dependency and reads more quantitatively for many segments:\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef plot_vj_heatmap(clone_df):\n    vj = clone_df.pivot_table(index='v_gene', columns='j_gene', values='frequency', aggfunc='sum', fill_value=0)\n    fig, ax = plt.subplots(figsize=(8, 6))\n    sns.heatmap(vj, cmap='viridis', ax=ax)\n    ax.set_title('V-J pairing frequency')\n    return fig\n```\n\n## CDR3 spectratype: length distribution reveals clonal structure\n\nThe spectratype is a histogram of CDR3 length. A roughly Gaussian, bell-shaped distribution indicates a diverse, polyclonal (naive-like) repertoire; skew or discrete spikes at particular lengths indicate clonal expansion(s). The classic immunoscope spectratype (and VDJtools `CalcSpectratype`) bins nucleotide length, where in-frame clones sit 3 nt apart and the periodicity is part of the readout; amino-acid length is a common simplification - state which is plotted. Weighting by read\u002FUMI frequency shows expansions; weighting by unique clonotypes shows the underlying diversity - the two views can look opposite, so label which is plotted.\n\n```python\ndef plot_spectratype(clone_df, length_col='cdr3_length'):\n    fig, ax = plt.subplots(figsize=(9, 5))\n    bins = range(clone_df[length_col].min(), clone_df[length_col].max() + 2)\n    ax.hist(clone_df[length_col], bins=bins, weights=clone_df['frequency'], color='steelblue')\n    ax.set_xlabel('CDR3 length (aa)')\n    ax.set_ylabel('Frequency')  # Gaussian = polyclonal; spikes = clonal expansion\n    return fig\n```\n\n## Clonal-space \u002F proportion: how much repertoire the big clones hold\n\nBin clones into frequency strata (Rare \u002F Small \u002F Medium \u002F Large \u002F Hyperexpanded) and stack their summed frequency. Because strata are defined on frequency, this view is comparatively depth-robust and shows clonal-space homeostasis at a glance. A treemap of top clones is an alternative when individual dominant clones matter.\n\n```python\nimport numpy as np\n\ndef plot_clonal_space(clone_df, sample_col='sample'):\n    # Frequency-based strata (immunarch homeo convention); frequency makes this depth-robust\n    edges = [0, 1e-4, 1e-3, 1e-2, 1e-1, 1.0]\n    labels = ['Rare', 'Small', 'Medium', 'Large', 'Hyperexpanded']\n    clone_df = clone_df.copy()\n    clone_df['stratum'] = pd.cut(clone_df['frequency'], bins=edges, labels=labels)\n    space = clone_df.groupby([sample_col, 'stratum'], observed=True)['frequency'].sum().unstack(fill_value=0)\n    fig, ax = plt.subplots(figsize=(8, 5))\n    space[labels].plot(kind='bar', stacked=True, ax=ax, colormap='viridis')\n    ax.set_ylabel('Fraction of repertoire')\n    return fig\n```\n\n## Clonal tracking across timepoints\n\nTrack individual clone frequencies over an ordered sample set (vaccination, infection, therapy). A line plot of the top clones, or an alluvial\u002Fstream for the same data, shows expansion, contraction, and persistence. Downsample timepoints to a common depth before declaring contraction - a clone scored absent at one timepoint is frequently below the sampling floor, not truly gone.\n\n```python\ndef plot_clone_tracking(clone_df, top_n=10, clone_col='cdr3_aa', time_col='timepoint'):\n    top = clone_df.groupby(clone_col)['frequency'].sum().nlargest(top_n).index\n    fig, ax = plt.subplots(figsize=(9, 5))\n    for clone in top:\n        d = clone_df[clone_df[clone_col] == clone].sort_values(time_col)\n        ax.plot(d[time_col], d['frequency'], marker='o', label=clone[:12])\n    ax.set_xlabel('Timepoint'); ax.set_ylabel('Clone frequency')\n    ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', fontsize=7)\n    return fig\n```\n\n## Rarefaction\u002Fextrapolation: the correct way to compare diversity\n\nA bare bar of Shannon (or observed richness) across samples of unequal depth is misleading - it plots depth as much as biology. The defensible comparison is a rarefaction\u002Fextrapolation curve: interpolate each sample down to (and extrapolate modestly above) a shared depth, then read diversity at a common x. iNEXT computes this for Hill numbers q=0\u002F1\u002F2 with confidence intervals (Hsieh et al. 2016 *Methods Ecol Evol* 7:1451; Chao et al. 2014 *Ecol Monogr* 84:45).\n\nR route (gold standard, gives CIs):\n\n```r\nlibrary(iNEXT)\n\n# count_list: named list of per-sample integer clonotype-count vectors\nout \u003C- iNEXT(count_list, q = c(0, 1, 2), datatype = 'abundance')\nggiNEXT(out, type = 1)  # diversity vs sample size, read at a common x\n```\n\nVDJtools route: `vdjtools RarefactionPlot -m metadata.txt output_dir\u002F`.\n\nPython resampling route (interpolation by multinomial subsampling) when iNEXT is unavailable:\n\n```python\ndef rarefaction_curve(counts, depths, reps=20, rng=None):\n    # Interpolate observed richness by drawing 'm' reads without-replacement-like via multinomial\n    rng = rng or np.random.default_rng(0)\n    counts = np.asarray(counts, dtype=float)\n    p = counts \u002F counts.sum()\n    total = int(counts.sum())\n    richness = []\n    for m in depths:\n        if m > total:  # interpolation only; do not extrapolate past observed depth here\n            richness.append(np.nan); continue\n        obs = [np.count_nonzero(rng.multinomial(m, p)) for _ in range(reps)]\n        richness.append(np.mean(obs))\n    return richness\n```\n\n## Overlap heatmap: pick a depth-robust metric\n\nAn N-by-N similarity heatmap summarizes pairwise repertoire overlap. The metric choice is the decision: Morisita-Horn is abundance-weighted and near-invariant to sample size, so it is the default across unequal depths; Jaccard (presence\u002Fabsence) is dominated by the shallower sample's depth and should not be compared across unequal-depth pairs. Compute the matrix in vdjtools-analysis on depth-normalized samples, then render it here. Label the metric in the title.\n\n```python\ndef plot_overlap_heatmap(overlap_matrix, metric='Morisita-Horn'):\n    fig, ax = plt.subplots(figsize=(7, 6))\n    sns.heatmap(overlap_matrix, annot=True, fmt='.2f', cmap='YlOrRd', vmin=0, vmax=1, square=True, ax=ax)\n    ax.set_title(f'Repertoire overlap ({metric})')  # state the metric; Jaccard is depth-biased\n    return fig\n```\n\n## Clonotype-similarity network\n\nNodes are CDR3s, edges connect sequences within a chosen distance, and clusters are candidate specificity groups. The network structure depends entirely on the threshold: too loose chains distinct clones together, too tight fragments real groups. State the threshold and metric, and test sensitivity before interpreting clusters. Same-length CDR3s with Hamming distance is the conservative default; Levenshtein allows indels.\n\n```python\nimport networkx as nx\nfrom rapidfuzz.distance import Levenshtein\n\ndef build_similarity_network(clone_df, max_norm_dist=0.15, clone_col='cdr3_aa'):\n    # normalized_similarity in [0,1]; edge when 1 - similarity \u003C= threshold. Structure is threshold-dependent.\n    clones = clone_df[clone_col].unique()\n    g = nx.Graph()\n    g.add_nodes_from(clones)\n    for i, a in enumerate(clones):\n        for b in clones[i + 1:]:\n            if 1 - Levenshtein.normalized_similarity(a, b) \u003C= max_norm_dist:\n                g.add_edge(a, b)\n    return g\n```\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Diversity \"differs\" between groups but tracks library size | Bare Shannon\u002Frichness bar across unequal depth | Downsample to common depth or plot rarefaction curves read at a shared x (iNEXT\u002FRarefactionPlot) |\n| Overlap heatmap shows huge differences driven by one shallow sample | Jaccard\u002Fshared-count on raw, unequal-depth counts | Use Morisita-Horn on depth-normalized samples; label the metric |\n| Network clusters change completely on re-run with a new cutoff | Arbitrary distance threshold; single-linkage chaining | Fix and report the metric + threshold; run a sensitivity sweep; prefer Hamming on same-length CDR3s |\n| Two figures disagree on sharing\u002Fdiversity | Built on different clonotype definitions (nt vs aa, +\u002F- V\u002FJ) | Hold one clonotype definition constant across all figures in a comparison and state it |\n| Spectratype \"expansion\" vanishes when re-plotted | Switched between frequency-weighted and clonotype-weighted histogram | Choose one weighting per figure and label it (frequency shows expansions) |\n| V-usage differences between batches look biological | Multiplex-PCR primer bias | Compare usage only within one protocol, or use UMI\u002F5'RACE data |\n| `plt.cm.get_cmap(name, N)` raises AttributeError | Removed in matplotlib 3.9+ | Use `plt.get_cmap(name)` or `matplotlib.colormaps[name].resampled(N)` |\n\n## Related Skills\n\n- vdjtools-analysis - Compute the diversity\u002Foverlap inputs (depth-normalized)\n- mixcr-analysis - Produce clonotype tables\n- scirpy-analysis - Single-cell clonal-expansion overlays\n- data-visualization\u002Fggplot2-fundamentals - General ggplot2 grammar\n- data-visualization\u002Fheatmaps-clustering - Overlap\u002Fusage heatmap techniques\n\n## References\n\n- Shugay M, et al. VDJtools: unifying post-analysis of T cell receptor repertoires. *PLoS Comput Biol* 2015; 11(11):e1004503. (PlotFancyVJUsage, RarefactionPlot, overlap metrics.)\n- Chao A, Gotelli NJ, Hsieh TC, Sander EL, Ma KH, Colwell RK, Ellison AM. Rarefaction and extrapolation with Hill numbers. *Ecol Monogr* 2014; 84(1):45-67. (Interpolation\u002Fextrapolation framework.)\n- Hsieh TC, Ma KH, Chao A. iNEXT: an R package for rarefaction and extrapolation of species diversity (Hill numbers). *Methods Ecol Evol* 2016; 7(12):1451-1456. (Rarefaction\u002Fextrapolation curves with CIs.)\n- Greiff V, et al. A bioinformatic framework for immune repertoire diversity profiling. *Genome Med* 2015; 7:49. (Hill-number diversity profiling of repertoires.)\n- Venturi V, et al. Sharing of T cell receptors in antigen-specific responses is driven by convergent recombination. *PNAS* 2006; 103(49):18691-18696. (aa-clonotype sharing inflated by convergence.)\n- Chao A. Nonparametric estimation of the number of classes in a population. *Scand J Stat* 1984; 11:265-270. (Chao1 richness estimator.)\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29,"goal_approach_exempt":30},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","mixed","2026-09-20","tcr-bcr-analysis\u002Frepertoire-visualization\u002FSKILL.md","VDJtools","GPTomics\u002FbioSkills",true,"main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-repertoire-visualization","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":38,"prompt":48,"zipAvailable":30},[39,42,45],{"tool":40,"command":41},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-tcr-bcr-analysis-repertoire-visualization",{"tool":43,"command":44},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-tcr-bcr-analysis-repertoire-visualization",{"tool":46,"command":47},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-tcr-bcr-analysis-repertoire-visualization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-repertoire-visualization\u002FSKILL.md",[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Frepertoire_plots.py","SCRIPT","脚本",8539,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-repertoire-visualization\u002Fexamples\u002Frepertoire_plots.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",4381,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-repertoire-visualization\u002Fusage-guide.md",[63,71,78,85,92,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":70},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":70},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":70},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":70},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":70},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":70},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]