{"data":{"slug":"github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-sample-group-sankey-plot-1568d7d459c8","title":"Generate Sankey Plot from Sample Annotation Table","summary":"Create a Sankey or alluvial plot from a sample annotation table with at least two categorical stage columns, such as risk group, response status, or subtype. The output includes a plot PDF, selected annotations, and session metadata.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-sample-group-sankey-plot-1568d7d459c8","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-sample-group-sankey-plot-1568d7d459c8","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-sample-group-sankey-plot-1568d7d459c8.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-sample-group-sankey-plot-1568d7d459c8\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Install required R packages before the first run using `Rscript scripts\/install_dependencies.R`. Ensure the input file contains at least two stage columns and is in CSV or TSV format. For readability, use fewer than 8 unique values per stage and fewer than 5 stages total.","instructions":"---\nname: sample-group-sankey-plot\ndescription: \"Use when generating Sankey or alluvial plots from sample annotation tables where rows are samples and selected columns are categorical stages such as risk group, response status, subtype, or cohort labels. NOT for: gene network flow analysis, continuous-value trajectories, or graph-structured pathway visualization.\"\nlicense: MIT\nskill-author: AIPOCH\n---\n\n# Sample Group Sankey Plot\n\nBuilds a reproducible Sankey\/alluvial visualization from a tabular sample annotation file and exports the selected annotations, lodes-format table, plot PDF, and session metadata.\n\n## Input Validation\n\nThis skill accepts: a sample annotation table in CSV or TSV format where rows are samples and selected columns are categorical stages (e.g., risk group, response status, subtype, cohort label). At least 2 stage columns are required.\n\nIf the user's request does not involve generating a Sankey or alluvial flow diagram from categorical sample annotations \u2014 for example, asking to visualize a gene regulatory network, plot continuous-value trajectories, analyze pathway flow, or process non-tabular data \u2014 do not proceed with the workflow. Instead respond:\n\n> \"sample-group-sankey-plot is designed to generate Sankey\/alluvial plots from categorical sample annotation tables. Your request appears to be outside this scope. Please provide a sample annotation table with at least 2 categorical stage columns, or use a more appropriate tool for gene network visualization or pathway analysis.\"\n\n**Readability guidance:** Sankey plots are recommended for fewer than 8 unique values per stage and fewer than 5 stages total. For larger inputs, filter or aggregate categories before plotting to ensure readable output.\n\n## Agent Response Contract\n\nAfter a successful run, report to the caller:\n\n```\nSankey plot generated successfully.\nStages plotted : <comma-separated stage column names>\nSamples        : <row count>\nOutput prefix  : <output_prefix>\nOutputs:\n  table\/selected_annotations.csv\n  table\/sankey_lodes.csv\n  plot\/<output_prefix>.pdf\n  data\/session_info.txt\nReadability warnings (if any): <advisory messages or \"none\">\n```\n\nIf the script exits with a non-zero status, surface the SKILL_* error code and message verbatim. Do not attempt to continue or retry silently.\n\n## When to Read External Files\n\n| Situation | File to Read | Purpose |\n|-----------|--------------|---------|\n| **Need to run analysis** | `scripts\/main.R` | Execute: `Rscript scripts\/main.R --input_file ... --output_dir ...` |\n| **Need algorithm details** | `references\/algorithm.md` | Alluvial transformation logic, assumptions, and plotting choices |\n| **Encounter errors** | `references\/troubleshooting.md` | Common errors and solutions |\n| **Need CLI examples** | `references\/cli-guide.md` | Detailed CLI examples |\n| **Need test data** | `tests\/data\/` | Sample annotation tables for smoke tests and regression checks |\n\n\u2192 Reference files `algorithm.md`, `troubleshooting.md`, and `cli-guide.md` are in `references\/`. If absent, rely on the Error Handling table below for common issues.\n\n---\n\n## Usage\n\n### Environment Setup\n\nInstall required R packages before the first run:\n\n```bash\nRscript scripts\/install_dependencies.R\n```\n\nNote: `install_dependencies.R` installs from CRAN without version pinning. Tested with ggalluvial >= 0.12.5 and ggplot2 >= 3.4.0. For reproducible CI environments, consider using `remotes::install_version()`.\n\n### Basic Command\n\n```bash\nRscript scripts\/main.R \\\n  --input_file .\/annotations.csv \\\n  --output_dir .\/output \\\n  --columns risk,Responder \\\n  --seed 42\n```\n\n---\n\n## Arguments\n\n| Short | Long | Type | Default | Description |\n|-------|------|------|---------|-------------|\n| `-i` | `--input_file` | character | **required** | Input CSV\/TSV annotation table |\n| `-o` | `--output_dir` | character | `.\/output\/` | Output directory |\n| `-c` | `--columns` | character | all columns | Comma-separated stage columns to include in the plot. When omitted, all columns in the file are used as stages. |\n| `-p` | `--output_prefix` | character | `sankey_plot` | Prefix for generated output files (alphanumeric, dot, underscore, or hyphen characters only) |\n|  | `--width` | numeric | `7` | Plot width in inches |\n|  | `--height` | numeric | `5` | Plot height in inches |\n|  | `--alpha` | numeric | `0.5` | Flow transparency between `0` and `1` |\n|  | `--label_size` | numeric | `4.5` | Stratum label size |\n|  | `--missing_label` | character | `Missing` | Replacement label for blank or `NA` strata |\n|  | `--title` | character | empty | Optional plot title |\n| `-s` | `--seed` | integer | `42` | Random seed recorded for reproducibility |\n|  | `--timeout` | integer | `3600` | Maximum allowed elapsed runtime in seconds; use `0` to disable |\n\n---\n\n## Input Format\n\n### Annotation Table (`input_file`)\n\nDelimited text file where rows represent samples and each selected column is a categorical stage shown in the Sankey plot.\n\n```csv\nSampleID,risk,Responder,Subtype\nS1,High,Yes,Basal\nS2,Low,No,LumA\nS3,High,Yes,Basal\nS4,Low,No,LumB\n```\n\n**Requirements:**\n- The file must contain at least 2 columns if `--columns` is omitted.\n- Each selected column must exist in the file header.\n- Selected columns are interpreted as categorical stages and will be converted to character values.\n- Blank strings and `NA` values are replaced with `--missing_label`.\n- CSV and TSV inputs are supported.\n- Recommended: fewer than 8 unique values per stage and fewer than 5 stages total for readable plots.\n\n---\n\n## Output Files\n\n| File | Description |\n|------|-------------|\n| `table\/selected_annotations.csv` | Filtered table containing only the plotted stage columns |\n| `table\/sankey_lodes.csv` | Long-format lodes table used to build the Sankey plot |\n| `plot\/{output_prefix}.pdf` | Sankey\/alluvial plot as a PDF file; default filename is `sankey_plot.pdf` |\n| `data\/session_info.txt` | R session information and runtime parameters |\n\n### selected_annotations.csv\n\n| Column | Type | Description |\n|--------|------|-------------|\n| stage columns | character | One column per plotted stage in original order |\n\n### sankey_lodes.csv\n\n| Column | Type | Description |\n|--------|------|-------------|\n| `sample_id` | character | Synthetic row identifier used as the alluvium key |\n| `x` | character | Stage name |\n| `stratum` | character | Category label for the stage |\n\n---\n\n## Workflow\n\n### Step 1: Validate Input\n- Check that the input file exists and is readable.\n- Detect CSV vs TSV input.\n- Validate that at least 2 stage columns are available.\n- Validate that user-specified columns exist.\n\n### Step 2: Prepare Sankey Data\n- Subset the selected stage columns.\n- Replace missing or blank labels.\n- Add a row-level `sample_id` identifier.\n- Convert the table with `ggalluvial::to_lodes_form()`.\n\n### Step 2a: Readability Advisories\nAfter column selection, the script emits `log_warn` advisories when:\n- More than 5 stages are selected: `\"More than 5 stages selected; plot may be hard to read. Consider filtering.\"`\n- A stage has more than 8 unique values: `\"Stage <name> has <n> unique values; consider aggregating for readability.\"`\n\nThese are advisory only \u2014 the script continues and produces the plot.\n\n### Step 3: Generate Visualization\n- Build the Sankey\/alluvial plot with `geom_flow()` and `geom_stratum()`.\n- Render stratum labels.\n- Save the plot as PDF.\n\n### Step 4: Record Outputs\n- Save the selected annotations and lodes-format table as CSV files.\n- Save `sessionInfo()` and runtime arguments for reproducibility.\n\n---\n\n## Examples\n\n### Reproduce the Original Two-Column Plot\n\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_annotations.csv \\\n  -o tests\/output \\\n  -c risk,Responder\n```\n\n### Plot Three Annotation Stages\n\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_annotations.csv \\\n  -o tests\/output_three_stage \\\n  -c risk,Responder,Subtype \\\n  --title \"Risk to response transitions\"\n```\n\n### Use All Columns Automatically\n\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/minimal_annotations.csv \\\n  -o tests\/output_all_columns\n```\n\n---\n\n## Error Handling\n\n### Common Errors\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| `SKILL_FILE_NOT_FOUND` | Input file does not exist | Check `--input_file` |\n| `SKILL_EMPTY_DATA` | The input file has zero rows or fewer than 2 usable columns | Provide a non-empty table with at least 2 stage columns |\n| `SKILL_MISSING_COLUMNS` | A requested stage column is absent | Correct `--columns` or fix the input header |\n| `SKILL_INVALID_PARAMETER` | Width, height, alpha, label size, or output prefix is invalid | Provide valid arguments per the Arguments table |\n| `SKILL_DEPENDENCY_MISSING` | A required R package is unavailable | Run `Rscript scripts\/install_dependencies.R` |\n| `SKILL_IO_ERROR` | Output directory cannot be created or written | Check permissions on `--output_dir` |\n\n**IF error persists**, READ: `references\/troubleshooting.md`\n\n---\n\n## Testing\n\n### Test with Sample Data\n\n```bash\nRscript scripts\/install_dependencies.R\n\nRscript scripts\/main.R --help\n\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_annotations.csv \\\n  -o tests\/output \\\n  -c risk,Responder,Subtype\n\nRscript tests\/test_skill.R\n\nRscript tests\/run_smoke_test.R\n```\n\n### Validation Commands\n\n```bash\nls -la tests\/output\/table\nls -la tests\/output\/plot\nls -la tests\/output\/data\n```\n\n---\n\n## References\n\n1. Brunson JC (2020) ggalluvial: Layered Grammar for Alluvial Plots. *Journal of Open Source Software*. doi:10.21105\/joss.02017\n2. Wickham H (2016) *ggplot2: Elegant Graphics for Data Analysis*. Springer. doi:10.1007\/978-3-319-24277-4\n\n**For detailed algorithm**, READ: `references\/algorithm.md`\n","use_cases":["Visualize sample flow across risk groups and response statuses","Compare subtype distributions across different cohorts","Track sample progression through multiple categorical stages"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/awesome-med-research-skills\/Data%20Analysis\/sample-group-sankey-plot\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T07:31:07.000000Z","updated_at":"2026-11-24T07:13:22.000000Z","seo_title":"Generate Sankey Plot from Sample Annotation Table","seo_description":"Create Sankey or alluvial plots from sample annotation tables with categorical stages. Requires CSV\/TSV file with at least 2 stage columns.","seo_keywords":["Sankey plot from annotation table","Alluvial plot for sample data","Categorical stage visualization","Sample annotation to plot","Generate Sankey from CSV"]}}