[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECS8X513NMXHHW9CSA33EF":3,"skill-same:01M7ECS8X513NMXHHW9CSA33EF":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":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7ECS8X513NMXHHW9CSA33EF","bio-data-visualization-oncoprint-mutation-matrices",null,"Build OncoPrint and co-mutation matrix plots from somatic-variant cohorts using ComplexHeatmap, maftools, and comut.py with alteration-type stacking, sample ordering by mutational burden, mutual-exclusivity overlays, and clinical annotation tracks. Use when visualizing per-sample mutation patterns across recurrent driver genes, comparing alteration classes, or identifying mutually-exclusive \u002F co-occurring driver pairs.","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-data-visualization-oncoprint-mutation-matrices\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-data-visualization-oncoprint-mutation-matrices\ndescription: Build OncoPrint and co-mutation matrix plots from somatic-variant cohorts using ComplexHeatmap, maftools, and comut.py with alteration-type stacking, sample ordering by mutational burden, mutual-exclusivity overlays, and clinical annotation tracks. Use when visualizing per-sample mutation patterns across recurrent driver genes, comparing alteration classes, or identifying mutually-exclusive \u002F co-occurring driver pairs.\ntool_type: mixed\nprimary_tool: ComplexHeatmap\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"data-visualization\u002Foncoprint-mutation-matrices\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: ComplexHeatmap 2.18+, maftools 2.18+, comut 0.0.3+, MAFtools requires R 4.0+; comut.py requires pandas 2.0+, matplotlib 3.8+.\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`\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.\n\n# OncoPrint and Mutation Matrix Plots\n\n**\"Plot mutations across a cohort\"** -> Render a gene-by-sample matrix where each cell stacks colored rectangles encoding alteration class (missense, truncating, splice, copy-gain, copy-loss, fusion). Sort samples by burden, optionally split by clinical group, and overlay co-mutation \u002F mutual-exclusivity annotations. OncoPrint (Cerami 2012 *Cancer Discov* 2:401; canonical at cBioPortal) is the genre-defining visualization.\n\n- R: `ComplexHeatmap::oncoPrint`, `maftools::oncoplot`\n- Python: `comut.CoMut`, `cbioportal`-style implementations\n\n## The Single Most Important Modern Insight -- Cell Stacking Encodes Multiple Alterations Per Cell\n\nOncoPrint differs from a generic heatmap because each cell can encode multiple alterations simultaneously through *stacked* rectangles. A patient with both a missense and a copy-gain in TP53 shows one cell with two overlapping colored rectangles (e.g., green diamond inside red square). This stacking is the whole point — it preserves the multi-modal alteration landscape that flattening to a single category destroys.\n\nIn ComplexHeatmap's `oncoPrint`, the `alter_fun` argument is the rendering specification: a named list of functions, one per alteration class, each drawing its rectangle inside the cell. Get this right and the figure works; get it wrong and overlapping alterations are invisible.\n\n## Decision Tree by Cohort and Question\n\n| Question | Sort by | Display |\n|----------|---------|---------|\n| Which genes are most altered? | Gene frequency (default) | Bar above samples (sample TMB); bar right of genes (gene frequency) |\n| Per-patient burden patterns | Sample burden | TMB bar on top; sample-name labels |\n| Subtype-driver enrichment | Clinical group then burden | `column_split` by group; per-group frequency right bar |\n| Mutual exclusivity (BRAF vs NRAS) | Custom (alphabetic-by-mutation pattern) | Memo sort; overlay log10(OR) heatmap |\n| Co-occurrence (TP53 + MYC) | Custom | Same pattern; positive OR coloring |\n| Driver vs passenger comparison | Two panels | Concatenate two oncoPrints horizontally |\n\n## ComplexHeatmap::oncoPrint -- Canonical Implementation\n\n**Goal:** Render a cohort mutation matrix with stacked alteration-class encoding, sample annotations, and a sample-sorted, gene-frequency-ranked layout.\n\n**Approach:** Convert the MAF\u002Fvariant table to a gene-by-sample matrix of `;`-delimited alteration strings; define `alter_fun` rendering one rectangle per class; pass to `oncoPrint()` with column annotations.\n\n```r\nlibrary(ComplexHeatmap)\nlibrary(circlize)\n\n# Input: matrix where each cell is a string like 'Missense;Amp' or '' for no alteration\n# Rows = genes; columns = samples\n\n# Color per alteration class\ncol \u003C- c('Missense'   = '#56B4E9',\n         'Truncating' = '#000000',\n         'Splice'     = '#CC79A7',\n         'Amp'        = '#D55E00',\n         'HomDel'     = '#0072B2',\n         'Fusion'     = '#009E73')\n\n# alter_fun -- one function per class, each drawing inside the cell\nalter_fun \u003C- list(\n    background = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h - unit(0.5, 'mm'),\n                  gp = gpar(fill = '#EEEEEE', col = NA)),\n    Amp = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h - unit(0.5, 'mm'),\n                  gp = gpar(fill = col['Amp'], col = NA)),\n    HomDel = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h - unit(0.5, 'mm'),\n                  gp = gpar(fill = col['HomDel'], col = NA)),\n    Missense = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h * 0.5,\n                  gp = gpar(fill = col['Missense'], col = NA)),\n    Truncating = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h * 0.33,\n                  gp = gpar(fill = col['Truncating'], col = NA)),\n    Splice = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h * 0.25,\n                  gp = gpar(fill = col['Splice'], col = NA)),\n    Fusion = function(x, y, w, h)\n        grid.points(x, y, pch = 17, size = unit(2, 'mm'),\n                    gp = gpar(col = col['Fusion'])))\n\n# Clinical column annotation\nha_clin \u003C- HeatmapAnnotation(\n    Subtype = clinical$subtype,\n    Stage   = clinical$stage,\n    col = list(Subtype = c(Luminal='#0072B2', Basal='#D55E00', HER2='#009E73'),\n               Stage   = c(I='#FFFFCC', II='#FED976', III='#FD8D3C', IV='#BD0026')))\n\noncoPrint(mat,\n          alter_fun = alter_fun,\n          col = col,\n          top_annotation = ha_clin,\n          column_title = 'TCGA-BRCA mutation landscape',\n          row_names_gp = gpar(fontsize = 8),\n          pct_gp = gpar(fontsize = 7),\n          show_pct = TRUE,\n          remove_empty_columns = FALSE,\n          remove_empty_rows = FALSE)\n```\n\n## maftools::oncoplot -- Faster Onboarding\n\nFor TCGA-style MAF files, `maftools::oncoplot` is the lower-friction option:\n\n```r\nlibrary(maftools)\nmaf \u003C- read.maf(maf = 'tcga.maf', clinicalData = clinical)\noncoplot(maf = maf,\n         top = 20,                            # top 20 mutated genes\n         clinicalFeatures = c('Subtype', 'Stage'),\n         annotationColor = list(Subtype = c(Luminal='#0072B2', Basal='#D55E00'),\n                                 Stage = c(I='#FFFFCC', IV='#BD0026')),\n         sortByAnnotation = TRUE,\n         removeNonMutated = FALSE)\n```\n\nmaftools defaults handle alteration-class colors, sample sorting, and percentage bars automatically. Customization is more limited than ComplexHeatmap.\n\n## Mutual Exclusivity and Co-Occurrence\n\n```r\n# maftools provides somaticInteractions\nsi \u003C- somaticInteractions(maf = maf, top = 20,\n                          pvalue = c(0.05, 0.01),\n                          fontSize = 0.7)\n# Plot returns a matrix of -log10(p) with sign by direction (+ co-occur, - mutex)\n```\n\nMutual-exclusivity testing on small cohorts (N \u003C 50) is underpowered; reported \"significant\" mutex on n=20 with 2 mutations each is uninterpretable. Aggregate to larger cohorts (TCGA + ICGC pan-cancer) or report effect size with CI rather than p-value.\n\n**Fisher exact vs DISCOVER:** standard 2x2 Fisher tests sample-mutation pairs, ignoring per-gene mutation rate background. DISCOVER (Canisius 2016 *Genome Biol* 17:261) models per-tumor mutation probability and is preferred for pan-cancer analyses where mutation rate varies 100× across samples.\n\n## comut.py -- Python Equivalent\n\n```python\nimport comut\nimport pandas as pd\n\n# Long-format: columns = sample, category (gene), value (alteration class)\ntoy_comut = comut.CoMut()\ntoy_comut.add_categorical_data(\n    data=mutation_long_df,\n    name='Mutations',\n    category_order=top_genes,\n    value_order=['Truncating', 'Missense', 'Splice', 'Amp', 'HomDel'],\n    mapping={'Truncating': '#000000', 'Missense': '#56B4E9',\n             'Splice': '#CC79A7', 'Amp': '#D55E00', 'HomDel': '#0072B2'})\n\ntoy_comut.add_categorical_data(\n    data=clinical_long_df,\n    name='Subtype',\n    mapping={'Luminal': '#0072B2', 'Basal': '#D55E00'})\n\ntoy_comut.add_continuous_data(\n    data=tmb_long_df,\n    name='TMB',\n    mapping='viridis',\n    value_range=(0, 30))\n\ntoy_comut.plot_comut(figsize=(12, 8))\ntoy_comut.figure.savefig('comut.pdf', dpi=300, bbox_inches='tight')\n```\n\n## Per-Method Failure Modes\n\n### Alterations flattened to a single class\n\n**Trigger:** Reducing each cell to a single most-severe alteration, losing the stack.\n\n**Mechanism:** Loses the multi-alteration biology (e.g., MYC amp + missense in TP53).\n\n**Symptom:** OncoPrint looks like a simple heatmap; co-occurring multi-class events invisible.\n\n**Fix:** Build the cell as `;`-separated alteration string; define `alter_fun` for each class.\n\n### Sample sort by gene 1 frequency only\n\n**Trigger:** Default `oncoPrint` sorts samples by altered-gene-1 status; weakens the \"memo sort\" pattern.\n\n**Mechanism:** True OncoPrint uses memoSort (Cerami 2012) which sorts by the binary altered-or-not pattern across the top genes.\n\n**Symptom:** Samples with the same alteration profile are not adjacent; \"staircase\" pattern lost.\n\n**Fix:** ComplexHeatmap `oncoPrint` uses memoSort by default; do NOT override `column_order` unless intentional.\n\n### Showing only mutated samples (`remove_empty_columns = TRUE`)\n\n**Trigger:** Default in some implementations.\n\n**Mechanism:** Drops samples with no mutations in the displayed genes — but those samples ARE part of the cohort.\n\n**Symptom:** Sample count differs from cohort N; denominator-based percentages wrong.\n\n**Fix:** `remove_empty_columns = FALSE` to preserve all samples; percentages now reflect true cohort fraction.\n\n### Hypermutators dominate visual\n\n**Trigger:** Cohort with 1-2 POLE-mutant or MSI-H samples; TMB bar saturates.\n\n**Mechanism:** Hypermutator TMB is 10-100× the typical sample.\n\n**Symptom:** All other samples' TMB bars are invisible; one column dominates.\n\n**Fix:** Log-transform the TMB annotation: `anno_barplot(log10(tmb + 1))`; OR cap with `ylim`.\n\n### Mutex\u002Fco-occurrence p-values overinterpreted on small cohorts\n\n**Trigger:** Fisher exact test on N \u003C 50 with low mutation counts.\n\n**Mechanism:** With 2 mutations vs 3 mutations in 20 samples, all p-values are dominated by noise.\n\n**Symptom:** \"Significant mutex\" claim from a tiny pilot.\n\n**Fix:** Aggregate to ≥100 samples for credible mutex; use DISCOVER (Canisius 2016) instead of Fisher when mutation rate varies 100× across samples.\n\n## Small-Cohort Regime (N = 20-50)\n\nFor rare-cancer cohorts where N \u003C 50, the standard OncoPrint + Fisher mutex pipeline is statistically uninterpretable:\n\n| Action | What to do |\n|--------|------------|\n| Report per-gene frequencies | Use exact-binomial CI (Clopper-Pearson via `binom.test`) — Wald CI is invalid at low frequency |\n| Do NOT report mutex p-values | Fisher exact on 2x2 with cell counts ≤ 5 has no power; the \"significant\" mutex finding is noise |\n| Hypothesis generation only | Pool with TCGA Pan-Cancer + ICGC for credible mutex; treat the cohort as the *replication* not the discovery |\n| Co-occurrence reporting | OR with Haldane-Anscombe 0.5 correction for zero cells; report alongside cohort N |\n\nShow the OncoPrint for visual transparency, but the per-gene-frequency *table* (with exact-binomial CIs) is the load-bearing scientific output, not the mutex test.\n\n## Reconciliation: When Implementations Differ\n\n| Pattern | Cause | Action |\n|---------|-------|--------|\n| ComplexHeatmap and maftools show different sample orders | Different memoSort defaults | Specify `sortByAnnotation` explicitly; report sort criterion in caption |\n| Percentage labels differ | `remove_empty_columns = TRUE` vs FALSE | Document denominator (cohort-N vs altered-N) |\n| Some alterations missing from a sample | Filtering: silent SNVs, low VAF | Document filtering criteria upstream |\n\n## Quantitative Thresholds\n\n| Threshold | Value | Source |\n|-----------|-------|--------|\n| Cohort N for valid mutex | ≥100 (pan-cancer); ≥50 (single-cohort with effect-size focus) | Common practice |\n| Display top genes | 10-25 in single panel | More creates visual clutter |\n| Sample N for OncoPrint | 50-1000 (above: switch to summary panel) | Visualization practical |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| Co-occurring multi-class events invisible | Single-class flattening | Use `;`-separated cells + alter_fun list |\n| Sample order doesn't show staircase | column_order override | Trust default memoSort |\n| Sample count differs from cohort | `remove_empty_columns = TRUE` | Set to FALSE |\n| TMB bar dominated by 1-2 samples | Hypermutators on linear scale | log10 + 1 transform |\n| Mutex p-values on N=20 | Underpowered | Aggregate cohorts; use DISCOVER |\n| Gene frequency right-bar mismatches percentages | Denominator definition | Document cohort-N vs altered-N |\n\n## References\n\n- Canisius S, Martens JWM, Wessels LFA. 2016. A novel independence test for somatic alterations in cancer shows that biology drives mutual exclusivity but chance explains most co-occurrence. *Genome Biol* 17:261.\n- Cerami E, Gao J, Dogrusoz U, et al. 2012. The cBio cancer genomics portal: an open platform for exploring multidimensional cancer genomics data. *Cancer Discov* 2(5):401-404.\n- Gao J, Aksoy BA, Dogrusoz U, et al. 2013. Integrative analysis of complex cancer genomics and clinical profiles using the cBioPortal. *Sci Signal* 6(269):pl1.\n- Gu Z, Eils R, Schlesner M. 2016. Complex heatmaps reveal patterns and correlations in multidimensional genomic data. *Bioinformatics* 32(18):2847-2849.\n- Mayakonda A, Lin DC, Assenov Y, Plass C, Koeffler HP. 2018. Maftools: efficient and comprehensive analysis of somatic variants in cancer. *Genome Res* 28(11):1747-1756.\n\n## Related Skills\n\n- data-visualization\u002Fheatmaps-clustering - Generic heatmap underlying oncoPrint\n- data-visualization\u002Flollipop-protein-maps - Per-gene mutation maps on protein domains\n- data-visualization\u002Fcolor-palettes - Alteration-class palette selection\n- clinical-databases\u002Fvariant-prioritization - Filter variants before OncoPrint\n- variant-calling\u002Fvariant-annotation - Annotate consequences upstream\n- copy-number\u002Fcnv-annotation - Integrate CNV calls into the oncoprint\n","## Version Compatibility\n\nReference examples tested with: ComplexHeatmap 2.18+, maftools 2.18+, comut 0.0.3+, MAFtools requires R 4.0+; comut.py requires pandas 2.0+, matplotlib 3.8+.\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`\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.\n\n# OncoPrint and Mutation Matrix Plots\n\n**\"Plot mutations across a cohort\"** -> Render a gene-by-sample matrix where each cell stacks colored rectangles encoding alteration class (missense, truncating, splice, copy-gain, copy-loss, fusion). Sort samples by burden, optionally split by clinical group, and overlay co-mutation \u002F mutual-exclusivity annotations. OncoPrint (Cerami 2012 *Cancer Discov* 2:401; canonical at cBioPortal) is the genre-defining visualization.\n\n- R: `ComplexHeatmap::oncoPrint`, `maftools::oncoplot`\n- Python: `comut.CoMut`, `cbioportal`-style implementations\n\n## The Single Most Important Modern Insight -- Cell Stacking Encodes Multiple Alterations Per Cell\n\nOncoPrint differs from a generic heatmap because each cell can encode multiple alterations simultaneously through *stacked* rectangles. A patient with both a missense and a copy-gain in TP53 shows one cell with two overlapping colored rectangles (e.g., green diamond inside red square). This stacking is the whole point — it preserves the multi-modal alteration landscape that flattening to a single category destroys.\n\nIn ComplexHeatmap's `oncoPrint`, the `alter_fun` argument is the rendering specification: a named list of functions, one per alteration class, each drawing its rectangle inside the cell. Get this right and the figure works; get it wrong and overlapping alterations are invisible.\n\n## Decision Tree by Cohort and Question\n\n| Question | Sort by | Display |\n|----------|---------|---------|\n| Which genes are most altered? | Gene frequency (default) | Bar above samples (sample TMB); bar right of genes (gene frequency) |\n| Per-patient burden patterns | Sample burden | TMB bar on top; sample-name labels |\n| Subtype-driver enrichment | Clinical group then burden | `column_split` by group; per-group frequency right bar |\n| Mutual exclusivity (BRAF vs NRAS) | Custom (alphabetic-by-mutation pattern) | Memo sort; overlay log10(OR) heatmap |\n| Co-occurrence (TP53 + MYC) | Custom | Same pattern; positive OR coloring |\n| Driver vs passenger comparison | Two panels | Concatenate two oncoPrints horizontally |\n\n## ComplexHeatmap::oncoPrint -- Canonical Implementation\n\n**Goal:** Render a cohort mutation matrix with stacked alteration-class encoding, sample annotations, and a sample-sorted, gene-frequency-ranked layout.\n\n**Approach:** Convert the MAF\u002Fvariant table to a gene-by-sample matrix of `;`-delimited alteration strings; define `alter_fun` rendering one rectangle per class; pass to `oncoPrint()` with column annotations.\n\n```r\nlibrary(ComplexHeatmap)\nlibrary(circlize)\n\n# Input: matrix where each cell is a string like 'Missense;Amp' or '' for no alteration\n# Rows = genes; columns = samples\n\n# Color per alteration class\ncol \u003C- c('Missense'   = '#56B4E9',\n         'Truncating' = '#000000',\n         'Splice'     = '#CC79A7',\n         'Amp'        = '#D55E00',\n         'HomDel'     = '#0072B2',\n         'Fusion'     = '#009E73')\n\n# alter_fun -- one function per class, each drawing inside the cell\nalter_fun \u003C- list(\n    background = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h - unit(0.5, 'mm'),\n                  gp = gpar(fill = '#EEEEEE', col = NA)),\n    Amp = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h - unit(0.5, 'mm'),\n                  gp = gpar(fill = col['Amp'], col = NA)),\n    HomDel = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h - unit(0.5, 'mm'),\n                  gp = gpar(fill = col['HomDel'], col = NA)),\n    Missense = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h * 0.5,\n                  gp = gpar(fill = col['Missense'], col = NA)),\n    Truncating = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h * 0.33,\n                  gp = gpar(fill = col['Truncating'], col = NA)),\n    Splice = function(x, y, w, h)\n        grid.rect(x, y, w - unit(0.5, 'mm'), h * 0.25,\n                  gp = gpar(fill = col['Splice'], col = NA)),\n    Fusion = function(x, y, w, h)\n        grid.points(x, y, pch = 17, size = unit(2, 'mm'),\n                    gp = gpar(col = col['Fusion'])))\n\n# Clinical column annotation\nha_clin \u003C- HeatmapAnnotation(\n    Subtype = clinical$subtype,\n    Stage   = clinical$stage,\n    col = list(Subtype = c(Luminal='#0072B2', Basal='#D55E00', HER2='#009E73'),\n               Stage   = c(I='#FFFFCC', II='#FED976', III='#FD8D3C', IV='#BD0026')))\n\noncoPrint(mat,\n          alter_fun = alter_fun,\n          col = col,\n          top_annotation = ha_clin,\n          column_title = 'TCGA-BRCA mutation landscape',\n          row_names_gp = gpar(fontsize = 8),\n          pct_gp = gpar(fontsize = 7),\n          show_pct = TRUE,\n          remove_empty_columns = FALSE,\n          remove_empty_rows = FALSE)\n```\n\n## maftools::oncoplot -- Faster Onboarding\n\nFor TCGA-style MAF files, `maftools::oncoplot` is the lower-friction option:\n\n```r\nlibrary(maftools)\nmaf \u003C- read.maf(maf = 'tcga.maf', clinicalData = clinical)\noncoplot(maf = maf,\n         top = 20,                            # top 20 mutated genes\n         clinicalFeatures = c('Subtype', 'Stage'),\n         annotationColor = list(Subtype = c(Luminal='#0072B2', Basal='#D55E00'),\n                                 Stage = c(I='#FFFFCC', IV='#BD0026')),\n         sortByAnnotation = TRUE,\n         removeNonMutated = FALSE)\n```\n\nmaftools defaults handle alteration-class colors, sample sorting, and percentage bars automatically. Customization is more limited than ComplexHeatmap.\n\n## Mutual Exclusivity and Co-Occurrence\n\n```r\n# maftools provides somaticInteractions\nsi \u003C- somaticInteractions(maf = maf, top = 20,\n                          pvalue = c(0.05, 0.01),\n                          fontSize = 0.7)\n# Plot returns a matrix of -log10(p) with sign by direction (+ co-occur, - mutex)\n```\n\nMutual-exclusivity testing on small cohorts (N \u003C 50) is underpowered; reported \"significant\" mutex on n=20 with 2 mutations each is uninterpretable. Aggregate to larger cohorts (TCGA + ICGC pan-cancer) or report effect size with CI rather than p-value.\n\n**Fisher exact vs DISCOVER:** standard 2x2 Fisher tests sample-mutation pairs, ignoring per-gene mutation rate background. DISCOVER (Canisius 2016 *Genome Biol* 17:261) models per-tumor mutation probability and is preferred for pan-cancer analyses where mutation rate varies 100× across samples.\n\n## comut.py -- Python Equivalent\n\n```python\nimport comut\nimport pandas as pd\n\n# Long-format: columns = sample, category (gene), value (alteration class)\ntoy_comut = comut.CoMut()\ntoy_comut.add_categorical_data(\n    data=mutation_long_df,\n    name='Mutations',\n    category_order=top_genes,\n    value_order=['Truncating', 'Missense', 'Splice', 'Amp', 'HomDel'],\n    mapping={'Truncating': '#000000', 'Missense': '#56B4E9',\n             'Splice': '#CC79A7', 'Amp': '#D55E00', 'HomDel': '#0072B2'})\n\ntoy_comut.add_categorical_data(\n    data=clinical_long_df,\n    name='Subtype',\n    mapping={'Luminal': '#0072B2', 'Basal': '#D55E00'})\n\ntoy_comut.add_continuous_data(\n    data=tmb_long_df,\n    name='TMB',\n    mapping='viridis',\n    value_range=(0, 30))\n\ntoy_comut.plot_comut(figsize=(12, 8))\ntoy_comut.figure.savefig('comut.pdf', dpi=300, bbox_inches='tight')\n```\n\n## Per-Method Failure Modes\n\n### Alterations flattened to a single class\n\n**Trigger:** Reducing each cell to a single most-severe alteration, losing the stack.\n\n**Mechanism:** Loses the multi-alteration biology (e.g., MYC amp + missense in TP53).\n\n**Symptom:** OncoPrint looks like a simple heatmap; co-occurring multi-class events invisible.\n\n**Fix:** Build the cell as `;`-separated alteration string; define `alter_fun` for each class.\n\n### Sample sort by gene 1 frequency only\n\n**Trigger:** Default `oncoPrint` sorts samples by altered-gene-1 status; weakens the \"memo sort\" pattern.\n\n**Mechanism:** True OncoPrint uses memoSort (Cerami 2012) which sorts by the binary altered-or-not pattern across the top genes.\n\n**Symptom:** Samples with the same alteration profile are not adjacent; \"staircase\" pattern lost.\n\n**Fix:** ComplexHeatmap `oncoPrint` uses memoSort by default; do NOT override `column_order` unless intentional.\n\n### Showing only mutated samples (`remove_empty_columns = TRUE`)\n\n**Trigger:** Default in some implementations.\n\n**Mechanism:** Drops samples with no mutations in the displayed genes — but those samples ARE part of the cohort.\n\n**Symptom:** Sample count differs from cohort N; denominator-based percentages wrong.\n\n**Fix:** `remove_empty_columns = FALSE` to preserve all samples; percentages now reflect true cohort fraction.\n\n### Hypermutators dominate visual\n\n**Trigger:** Cohort with 1-2 POLE-mutant or MSI-H samples; TMB bar saturates.\n\n**Mechanism:** Hypermutator TMB is 10-100× the typical sample.\n\n**Symptom:** All other samples' TMB bars are invisible; one column dominates.\n\n**Fix:** Log-transform the TMB annotation: `anno_barplot(log10(tmb + 1))`; OR cap with `ylim`.\n\n### Mutex\u002Fco-occurrence p-values overinterpreted on small cohorts\n\n**Trigger:** Fisher exact test on N \u003C 50 with low mutation counts.\n\n**Mechanism:** With 2 mutations vs 3 mutations in 20 samples, all p-values are dominated by noise.\n\n**Symptom:** \"Significant mutex\" claim from a tiny pilot.\n\n**Fix:** Aggregate to ≥100 samples for credible mutex; use DISCOVER (Canisius 2016) instead of Fisher when mutation rate varies 100× across samples.\n\n## Small-Cohort Regime (N = 20-50)\n\nFor rare-cancer cohorts where N \u003C 50, the standard OncoPrint + Fisher mutex pipeline is statistically uninterpretable:\n\n| Action | What to do |\n|--------|------------|\n| Report per-gene frequencies | Use exact-binomial CI (Clopper-Pearson via `binom.test`) — Wald CI is invalid at low frequency |\n| Do NOT report mutex p-values | Fisher exact on 2x2 with cell counts ≤ 5 has no power; the \"significant\" mutex finding is noise |\n| Hypothesis generation only | Pool with TCGA Pan-Cancer + ICGC for credible mutex; treat the cohort as the *replication* not the discovery |\n| Co-occurrence reporting | OR with Haldane-Anscombe 0.5 correction for zero cells; report alongside cohort N |\n\nShow the OncoPrint for visual transparency, but the per-gene-frequency *table* (with exact-binomial CIs) is the load-bearing scientific output, not the mutex test.\n\n## Reconciliation: When Implementations Differ\n\n| Pattern | Cause | Action |\n|---------|-------|--------|\n| ComplexHeatmap and maftools show different sample orders | Different memoSort defaults | Specify `sortByAnnotation` explicitly; report sort criterion in caption |\n| Percentage labels differ | `remove_empty_columns = TRUE` vs FALSE | Document denominator (cohort-N vs altered-N) |\n| Some alterations missing from a sample | Filtering: silent SNVs, low VAF | Document filtering criteria upstream |\n\n## Quantitative Thresholds\n\n| Threshold | Value | Source |\n|-----------|-------|--------|\n| Cohort N for valid mutex | ≥100 (pan-cancer); ≥50 (single-cohort with effect-size focus) | Common practice |\n| Display top genes | 10-25 in single panel | More creates visual clutter |\n| Sample N for OncoPrint | 50-1000 (above: switch to summary panel) | Visualization practical |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| Co-occurring multi-class events invisible | Single-class flattening | Use `;`-separated cells + alter_fun list |\n| Sample order doesn't show staircase | column_order override | Trust default memoSort |\n| Sample count differs from cohort | `remove_empty_columns = TRUE` | Set to FALSE |\n| TMB bar dominated by 1-2 samples | Hypermutators on linear scale | log10 + 1 transform |\n| Mutex p-values on N=20 | Underpowered | Aggregate cohorts; use DISCOVER |\n| Gene frequency right-bar mismatches percentages | Denominator definition | Document cohort-N vs altered-N |\n\n## References\n\n- Canisius S, Martens JWM, Wessels LFA. 2016. A novel independence test for somatic alterations in cancer shows that biology drives mutual exclusivity but chance explains most co-occurrence. *Genome Biol* 17:261.\n- Cerami E, Gao J, Dogrusoz U, et al. 2012. The cBio cancer genomics portal: an open platform for exploring multidimensional cancer genomics data. *Cancer Discov* 2(5):401-404.\n- Gao J, Aksoy BA, Dogrusoz U, et al. 2013. Integrative analysis of complex cancer genomics and clinical profiles using the cBioPortal. *Sci Signal* 6(269):pl1.\n- Gu Z, Eils R, Schlesner M. 2016. Complex heatmaps reveal patterns and correlations in multidimensional genomic data. *Bioinformatics* 32(18):2847-2849.\n- Mayakonda A, Lin DC, Assenov Y, Plass C, Koeffler HP. 2018. Maftools: efficient and comprehensive analysis of somatic variants in cancer. *Genome Res* 28(11):1747-1756.\n\n## Related Skills\n\n- data-visualization\u002Fheatmaps-clustering - Generic heatmap underlying oncoPrint\n- data-visualization\u002Flollipop-protein-maps - Per-gene mutation maps on protein domains\n- data-visualization\u002Fcolor-palettes - Alteration-class palette selection\n- clinical-databases\u002Fvariant-prioritization - Filter variants before OncoPrint\n- variant-calling\u002Fvariant-annotation - Annotate consequences upstream\n- copy-number\u002Fcnv-annotation - Integrate CNV calls into the oncoprint\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","mixed","2026-09-20","data-visualization\u002Foncoprint-mutation-matrices\u002FSKILL.md","ComplexHeatmap","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-data-visualization-oncoprint-mutation-matrices","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":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-data-visualization-oncoprint-mutation-matrices",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-data-visualization-oncoprint-mutation-matrices",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-data-visualization-oncoprint-mutation-matrices","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-data-visualization-oncoprint-mutation-matrices\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Foncoprint_phd.R","OTHER","其他",4278,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-data-visualization-oncoprint-mutation-matrices\u002Fexamples\u002Foncoprint_phd.R",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",4426,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-data-visualization-oncoprint-mutation-matrices\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",[],[]]