[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73JCYNFVNVKW1APTKFGTY8R":3,"skill-same:01M73JCYNFVNVKW1APTKFGTY8R":48},{"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":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73JCYNFVNVKW1APTKFGTY8R","seaborn-statistical-plots",null,"Statistical visualization on matplotlib with native pandas support. Auto aggregation, CIs, grouping for distributions (histplot, kdeplot), categorical (boxplot, violinplot), relational (scatterplot, lineplot), regression (regplot, lmplot), matrix (heatmap, clustermap), grids (pairplot, FacetGrid). Use for quick statistical summaries; matplotlib for fine control; plotly for interactive HTML.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"BSD-3-Clause","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fseaborn-statistical-plots\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"seaborn-statistical-plots\"\ndescription: \"Statistical visualization on matplotlib with native pandas support. Auto aggregation, CIs, grouping for distributions (histplot, kdeplot), categorical (boxplot, violinplot), relational (scatterplot, lineplot), regression (regplot, lmplot), matrix (heatmap, clustermap), grids (pairplot, FacetGrid). Use for quick statistical summaries; matplotlib for fine control; plotly for interactive HTML.\"\nlicense: BSD-3-Clause\n---\n\n# Seaborn — Statistical Plots\n\n## Overview\n\nSeaborn is a Python library for statistical data visualization built on top of matplotlib. It works directly with pandas DataFrames, automatically handles grouping by categorical variables, computes confidence intervals and kernel density estimates, and produces attractive publication-ready figures with minimal configuration. Seaborn separates axes-level functions (embeddable in custom layouts) from figure-level functions (with built-in faceting), enabling both quick exploratory analysis and structured multi-panel figures.\n\n## When to Use\n\n- Comparing gene expression, protein abundance, or measurement distributions across experimental conditions (treatment vs. control, cell lines, time points)\n- Generating grouped box plots, violin plots, or strip plots to show both summary statistics and individual data points simultaneously\n- Visualizing pairwise correlations in multi-gene or multi-feature datasets as annotated heatmaps\n- Plotting regression fits with confidence bands between continuous variables (e.g., cell viability vs. drug concentration)\n- Faceting a single plot type across multiple sample subsets, tissue types, or experimental batches in one call\n- Rapid exploratory analysis of a new dataset using `pairplot` to survey all pairwise relationships at once\n- Use `matplotlib` directly when you need pixel-level control over figure elements, complex mixed-type layouts, or non-statistical custom plots\n- Use `plotly` when the output must be interactive (hover tooltips, zoom, pan) or embedded in a web application\n\n## Prerequisites\n\n- **Python packages**: `seaborn>=0.13`, `matplotlib`, `pandas`, `numpy`\n- **Data requirements**: Pandas DataFrame in long-form (tidy) format; each observation is a row, each variable is a column\n- **Environment**: Standard Python environment; no GPU or special hardware required\n\n```bash\npip install \"seaborn>=0.13\" matplotlib pandas numpy scipy\n```\n\n## Quick Start\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n# Simulate gene expression across conditions\nrng = np.random.default_rng(42)\ndf = pd.DataFrame({\n    \"gene\":      [\"BRCA1\"] * 60 + [\"TP53\"] * 60,\n    \"condition\": [\"control\", \"treated\"] * 60,\n    \"log2_expr\": np.concatenate([\n        rng.normal(5.2, 0.8, 60),\n        rng.normal(6.1, 0.9, 60),\n    ])\n})\n\nsns.set_theme(style=\"ticks\", context=\"notebook\")\nsns.boxplot(data=df, x=\"gene\", y=\"log2_expr\", hue=\"condition\", palette=\"Set2\")\nplt.ylabel(\"log2 Expression\")\nplt.title(\"Gene Expression by Condition\")\nplt.tight_layout()\nplt.savefig(\"quickstart_boxplot.png\", dpi=150)\nprint(\"Saved quickstart_boxplot.png\")\n```\n\n## Core API\n\n### 1. Distribution Plots\n\nVisualize univariate distributions and compare them across groups. `histplot` bins data; `kdeplot` fits a smooth density estimate; `displot` is the figure-level wrapper that adds faceting.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(0)\nn = 200\ndf = pd.DataFrame({\n    \"log2_tpm\":  np.concatenate([rng.normal(4.5, 1.1, n), rng.normal(6.0, 1.3, n)]),\n    \"sample\":    [\"tumor\"] * n + [\"normal\"] * n,\n})\n\nfig, axes = plt.subplots(1, 3, figsize=(15, 4))\n\n# Histogram with density normalization and stacked hue groups\nsns.histplot(data=df, x=\"log2_tpm\", hue=\"sample\", stat=\"density\",\n             multiple=\"stack\", bins=30, ax=axes[0])\naxes[0].set_title(\"Histogram (stacked)\")\n\n# KDE with fill — bandwidth controlled by bw_adjust\nsns.kdeplot(data=df, x=\"log2_tpm\", hue=\"sample\", fill=True,\n            bw_adjust=0.8, alpha=0.4, ax=axes[1])\naxes[1].set_title(\"KDE (filled)\")\n\n# ECDF — useful for comparing cumulative distributions\nsns.ecdfplot(data=df, x=\"log2_tpm\", hue=\"sample\", ax=axes[2])\naxes[2].set_title(\"ECDF\")\n\nplt.tight_layout()\nplt.savefig(\"distributions.png\", dpi=150)\nprint(\"Saved distributions.png\")\n```\n\n```python\n# Bivariate KDE: joint distribution of two continuous variables\nrng = np.random.default_rng(1)\ndf2 = pd.DataFrame({\n    \"log2_rna\": rng.normal(5.5, 1.2, 300),\n    \"log2_prot\": rng.normal(4.8, 1.0, 300) + 0.6 * rng.normal(5.5, 1.2, 300),\n})\nsns.kdeplot(data=df2, x=\"log2_rna\", y=\"log2_prot\",\n            fill=True, levels=8, thresh=0.05, cmap=\"Blues\")\nplt.xlabel(\"log2 RNA (TPM)\")\nplt.ylabel(\"log2 Protein (iBAQ)\")\nplt.title(\"RNA–Protein Correlation Density\")\nplt.tight_layout()\nplt.savefig(\"bivariate_kde.png\", dpi=150)\nprint(\"Saved bivariate_kde.png\")\n```\n\n### 2. Categorical Plots\n\nCompare distributions or aggregated statistics across categorical groups. Axes-level functions (`boxplot`, `violinplot`, `stripplot`, `swarmplot`, `barplot`) accept an `ax=` parameter for embedding in custom layouts.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(2)\nconditions = [\"DMSO\", \"Drug A 1uM\", \"Drug A 10uM\", \"Drug B 1uM\", \"Drug B 10uM\"]\ndf = pd.DataFrame({\n    \"condition\": np.repeat(conditions, 30),\n    \"viability\": np.concatenate([\n        rng.normal(100, 5, 30),\n        rng.normal(92, 7, 30),\n        rng.normal(65, 10, 30),\n        rng.normal(88, 8, 30),\n        rng.normal(45, 12, 30),\n    ])\n})\n\nfig, axes = plt.subplots(1, 3, figsize=(18, 5))\n\n# Box plot — shows quartiles and outliers\nsns.boxplot(data=df, x=\"condition\", y=\"viability\",\n            palette=\"husl\", width=0.5, ax=axes[0])\naxes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=30, ha=\"right\")\naxes[0].set_title(\"Box Plot\")\n\n# Violin — KDE shape + inner quartile lines\nsns.violinplot(data=df, x=\"condition\", y=\"viability\",\n               inner=\"quart\", palette=\"muted\", ax=axes[1])\naxes[1].set_xticklabels(axes[1].get_xticklabels(), rotation=30, ha=\"right\")\naxes[1].set_title(\"Violin Plot\")\n\n# Strip plot overlaid on box — shows all individual points\nsns.boxplot(data=df, x=\"condition\", y=\"viability\",\n            palette=\"pastel\", width=0.5, ax=axes[2])\nsns.stripplot(data=df, x=\"condition\", y=\"viability\",\n              color=\"black\", alpha=0.4, size=3, jitter=True, ax=axes[2])\naxes[2].set_xticklabels(axes[2].get_xticklabels(), rotation=30, ha=\"right\")\naxes[2].set_title(\"Box + Strip\")\n\nplt.tight_layout()\nplt.savefig(\"categorical.png\", dpi=150)\nprint(\"Saved categorical.png\")\n```\n\n```python\n# Bar plot with mean ± 95% CI and individual points (swarm)\nfig, ax = plt.subplots(figsize=(8, 5))\nsns.barplot(data=df, x=\"condition\", y=\"viability\",\n            estimator=\"mean\", errorbar=\"ci\", palette=\"Set3\", ax=ax)\nsns.swarmplot(data=df, x=\"condition\", y=\"viability\",\n              color=\"black\", size=3, alpha=0.5, ax=ax)\nax.set_ylabel(\"Cell Viability (%)\")\nax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha=\"right\")\nplt.tight_layout()\nplt.savefig(\"barswarm.png\", dpi=150)\nprint(\"Saved barswarm.png\")\n```\n\n### 3. Relational Plots\n\nVisualize relationships between continuous variables. `scatterplot` and `lineplot` are axes-level; `relplot` is the figure-level wrapper that supports `col` and `row` faceting.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(3)\nn = 150\ndf = pd.DataFrame({\n    \"molecular_weight\": rng.uniform(200, 800, n),\n    \"logP\":             rng.uniform(-2, 6, n),\n    \"pIC50\":            rng.normal(6.5, 1.2, n),\n    \"target_class\":     rng.choice([\"kinase\", \"GPCR\", \"protease\"], n),\n    \"pass_lipinski\":    rng.choice([\"yes\", \"no\"], n, p=[0.7, 0.3]),\n})\n\n# Scatter with hue (categorical color) + size (continuous) + style (marker)\nsns.scatterplot(data=df, x=\"molecular_weight\", y=\"pIC50\",\n                hue=\"target_class\", size=\"logP\", style=\"pass_lipinski\",\n                sizes=(30, 120), alpha=0.7)\nplt.xlabel(\"Molecular Weight (Da)\")\nplt.ylabel(\"pIC50\")\nplt.title(\"Compound Bioactivity by Target Class\")\nplt.tight_layout()\nplt.savefig(\"relational_scatter.png\", dpi=150)\nprint(\"Saved relational_scatter.png\")\n```\n\n```python\n# Line plot with automatic mean aggregation and SD error band across replicates\ntimepoints = [0, 1, 2, 4, 8, 24]\ngroups = [\"untreated\", \"low_dose\", \"high_dose\"]\nrows = []\nfor grp, base in zip(groups, [100.0, 95.0, 80.0]):\n    for tp in timepoints:\n        for _ in range(5):  # 5 replicates\n            rows.append({\"timepoint_h\": tp, \"group\": grp,\n                         \"confluency\": base * np.exp(-0.02 * tp * (1 + rng.normal(0, 0.1)))})\ntime_df = pd.DataFrame(rows)\n\nsns.lineplot(data=time_df, x=\"timepoint_h\", y=\"confluency\",\n             hue=\"group\", style=\"group\", errorbar=\"sd\", markers=True, dashes=False)\nplt.xlabel(\"Time (h)\")\nplt.ylabel(\"Confluency (%)\")\nplt.title(\"Cell Growth Inhibition (mean ± SD, n=5)\")\nplt.tight_layout()\nplt.savefig(\"lineplot.png\", dpi=150)\nprint(\"Saved lineplot.png\")\n```\n\n### 4. Regression Plots\n\nFit linear (or polynomial\u002Flowess) models and visualize them with confidence bands. `regplot` is axes-level; `lmplot` is figure-level with faceting support.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(4)\nn = 120\ntumor_size = rng.uniform(0.5, 6.0, n)\nsurvival_months = 40 - 5 * tumor_size + rng.normal(0, 4, n)\ngrade = rng.choice([\"low\", \"high\"], n, p=[0.5, 0.5])\ndf = pd.DataFrame({\"tumor_size_cm\": tumor_size,\n                   \"survival_months\": survival_months,\n                   \"grade\": grade})\n\nfig, axes = plt.subplots(1, 2, figsize=(13, 5))\n\n# Linear regression with 95% CI band\nsns.regplot(data=df, x=\"tumor_size_cm\", y=\"survival_months\",\n            ci=95, scatter_kws={\"alpha\": 0.4, \"s\": 25}, ax=axes[0])\naxes[0].set_title(\"Linear Regression (95% CI)\")\n\n# Residuals plot — check for homoscedasticity\nsns.residplot(data=df, x=\"tumor_size_cm\", y=\"survival_months\",\n              scatter_kws={\"alpha\": 0.4, \"s\": 25}, ax=axes[1])\naxes[1].axhline(0, color=\"red\", linestyle=\"--\", linewidth=1)\naxes[1].set_title(\"Residuals vs Fitted\")\n\nplt.tight_layout()\nplt.savefig(\"regression.png\", dpi=150)\nprint(\"Saved regression.png\")\n```\n\n```python\n# lmplot — figure-level: separate regression lines per grade (hue) + facets\ng = sns.lmplot(data=df, x=\"tumor_size_cm\", y=\"survival_months\",\n               hue=\"grade\", col=\"grade\", ci=95,\n               scatter_kws={\"alpha\": 0.4}, height=4, aspect=1.1)\ng.set_axis_labels(\"Tumor Size (cm)\", \"Survival (months)\")\ng.set_titles(\"{col_name} grade\")\ng.savefig(\"lmplot_faceted.png\", dpi=150)\nprint(\"Saved lmplot_faceted.png\")\n```\n\n### 5. Matrix Plots\n\nVisualize rectangular data as color-encoded matrices. `heatmap` is axes-level; `clustermap` is figure-level and applies hierarchical clustering to rows and columns.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(5)\ngenes = [f\"GENE{i}\" for i in range(1, 9)]\nsamples = [f\"S{i}\" for i in range(1, 7)]\n\n# Simulate log2 fold-change matrix (rows=genes, cols=samples)\nlfc = pd.DataFrame(\n    rng.normal(0, 1.5, size=(8, 6)),\n    index=genes, columns=samples\n)\n# Inject a pattern: first 3 genes up in samples 1-3, down in 4-6\nlfc.iloc[:3, :3] += 2.5\nlfc.iloc[:3, 3:] -= 2.5\n\n# Correlation heatmap of numeric features\ndf_num = pd.DataFrame(\n    rng.standard_normal((80, 5)),\n    columns=[\"GeneA\", \"GeneB\", \"GeneC\", \"GeneD\", \"GeneE\"]\n)\ndf_num[\"GeneB\"] = df_num[\"GeneA\"] * 0.85 + rng.normal(0, 0.3, 80)\ncorr = df_num.corr()\n\nfig, axes = plt.subplots(1, 2, figsize=(14, 5))\n\nsns.heatmap(corr, annot=True, fmt=\".2f\", cmap=\"coolwarm\",\n            center=0, square=True, linewidths=0.5, ax=axes[0])\naxes[0].set_title(\"Pearson Correlation Heatmap\")\n\nsns.heatmap(lfc, cmap=\"RdBu_r\", center=0, annot=True, fmt=\".1f\",\n            linewidths=0.3, cbar_kws={\"label\": \"log2FC\"}, ax=axes[1])\naxes[1].set_title(\"log2 Fold Change Matrix\")\n\nplt.tight_layout()\nplt.savefig(\"heatmaps.png\", dpi=150)\nprint(\"Saved heatmaps.png\")\n```\n\n```python\n# Clustermap with hierarchical clustering and row\u002Fcolumn color annotations\nrng = np.random.default_rng(6)\nn_genes, n_samples = 30, 16\nexpr = pd.DataFrame(\n    rng.lognormal(mean=2.0, sigma=1.2, size=(n_genes, n_samples)),\n    index=[f\"GENE{i:03d}\" for i in range(n_genes)],\n    columns=[f\"{'T' if i \u003C 8 else 'N'}{i:02d}\" for i in range(n_samples)]\n)\n\n# Column annotation colors (tumor vs normal)\ncol_colors = [\"#D32F2F\" if c.startswith(\"T\") else \"#1976D2\" for c in expr.columns]\n\ng = sns.clustermap(\n    np.log2(expr + 1),\n    cmap=\"viridis\",\n    standard_scale=0,          # z-score across rows (genes)\n    method=\"ward\",\n    metric=\"euclidean\",\n    col_colors=col_colors,\n    figsize=(12, 10),\n    linewidths=0,\n    cbar_pos=(0.02, 0.8, 0.03, 0.15),\n    cbar_kws={\"label\": \"Row z-score\"},\n)\ng.ax_heatmap.set_xlabel(\"Sample\")\ng.ax_heatmap.set_ylabel(\"Gene\")\nplt.savefig(\"clustermap.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved clustermap.png\")\n```\n\n### 6. Multi-Variable Grids\n\nSurvey all pairwise relationships with `pairplot` or display a bivariate distribution with marginals using `jointplot`. For fully custom grid layouts, use `FacetGrid` directly.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(7)\nn = 60\ndf = pd.DataFrame({\n    \"cell_area\":      rng.normal(350, 60, n * 3),\n    \"nucleus_area\":   rng.normal(90, 15, n * 3),\n    \"mean_intensity\": rng.exponential(500, n * 3),\n    \"aspect_ratio\":   np.abs(rng.normal(1.3, 0.3, n * 3)),\n    \"cell_type\":      ([\"HeLa\"] * n + [\"MCF7\"] * n + [\"A549\"] * n),\n})\n\n# Pairplot — matrix of pairwise scatter + KDE on diagonal\ng = sns.pairplot(df, hue=\"cell_type\", corner=True,\n                 diag_kind=\"kde\", plot_kws={\"alpha\": 0.5, \"s\": 20})\ng.savefig(\"pairplot.png\", dpi=150)\nprint(\"Saved pairplot.png\")\n```\n\n```python\n# Jointplot — bivariate KDE with marginal histograms\ng = sns.jointplot(data=df, x=\"cell_area\", y=\"nucleus_area\",\n                  hue=\"cell_type\", kind=\"scatter\",\n                  marginal_kws={\"fill\": True, \"alpha\": 0.3})\ng.set_axis_labels(\"Cell Area (µm²)\", \"Nucleus Area (µm²)\")\ng.savefig(\"jointplot.png\", dpi=150)\nprint(\"Saved jointplot.png\")\n```\n\n```python\n# FacetGrid — custom layout: KDE of mean_intensity per cell type\ng = sns.FacetGrid(df, col=\"cell_type\", height=3.5, aspect=1.1,\n                  sharey=False)\ng.map(sns.histplot, \"mean_intensity\", bins=20, kde=True, color=\"steelblue\")\ng.set_axis_labels(\"Mean Intensity (AU)\", \"Count\")\ng.set_titles(\"{col_name}\")\ng.tight_layout()\ng.savefig(\"facetgrid_intensity.png\", dpi=150)\nprint(\"Saved facetgrid_intensity.png\")\n```\n\n## Key Concepts\n\n### Figure-Level vs Axes-Level Functions\n\nSeaborn has two tiers of functions with different return types and composability:\n\n| Feature | Axes-Level | Figure-Level |\n|---------|-----------|--------------|\n| **Examples** | `scatterplot`, `histplot`, `boxplot`, `heatmap`, `regplot` | `relplot`, `displot`, `catplot`, `lmplot` |\n| **Returns** | `matplotlib.axes.Axes` | `FacetGrid` \u002F `JointGrid` \u002F `PairGrid` |\n| **Faceting** | Manual (create subplots yourself) | Built-in (`col=`, `row=` params) |\n| **Sizing** | `figsize=` on parent figure | `height=` + `aspect=` per facet panel |\n| **Placement** | `ax=` parameter | Cannot be placed in an existing axes |\n| **Saving** | `plt.savefig(...)` | `g.savefig(...)` |\n| **Use when** | Combining different plot types in one figure | Quick multi-panel exploratory views |\n\n```python\n# Axes-level: place in a pre-allocated subplot grid\nfig, axes = plt.subplots(1, 2, figsize=(12, 5))\nsns.violinplot(data=df, x=\"cell_type\", y=\"cell_area\", ax=axes[0])\nsns.scatterplot(data=df, x=\"cell_area\", y=\"nucleus_area\", hue=\"cell_type\", ax=axes[1])\n```\n\n### Long-Form vs Wide-Form Data\n\nSeaborn semantic mappings (`hue`, `size`, `style`) require **long-form (tidy) data** where each variable is a column and each observation is a row. Some functions (`heatmap`, `clustermap`, `lineplot`) also accept wide-form.\n\n```python\n# Wide-form: unsuitable for hue\u002Fstyle mappings\n#   sample_A  sample_B  sample_C\n# 0      5.1       6.2       4.8\n\n# Long-form (preferred): melt wide → long\nwide = pd.DataFrame({\"sampleA\": [5.1, 4.3], \"sampleB\": [6.2, 5.9]})\nlong = wide.melt(var_name=\"sample\", value_name=\"log2_expr\")\n# → columns: sample, log2_expr\n```\n\n## Common Workflows\n\n### Workflow 1: Differential Expression Scatter with Significance Thresholds\n\n**Goal**: Visualize log2 fold-change vs -log10 p-value (volcano-style) with significance annotations, colored by regulation status, and labeled top hits.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(42)\nn = 500\nlfc   = rng.normal(0, 1.5, n)\npvals = 10 ** (-rng.exponential(1.5, n))        # skewed toward low significance\npvals = np.clip(pvals, 1e-20, 1.0)\ngenes = [f\"GENE{i:04d}\" for i in range(n)]\n\ndf_de = pd.DataFrame({\"gene\": genes, \"log2fc\": lfc, \"pvalue\": pvals})\ndf_de[\"neg_log10_p\"] = -np.log10(df_de[\"pvalue\"])\n\n# Classify regulation status\nlfc_thresh = 1.0\npadj_thresh = 0.05\ndf_de[\"sig\"] = \"NS\"\ndf_de.loc[(df_de[\"log2fc\"] >  lfc_thresh) & (df_de[\"pvalue\"] \u003C padj_thresh), \"sig\"] = \"Up\"\ndf_de.loc[(df_de[\"log2fc\"] \u003C -lfc_thresh) & (df_de[\"pvalue\"] \u003C padj_thresh), \"sig\"] = \"Down\"\n\npalette = {\"NS\": \"#AAAAAA\", \"Up\": \"#D32F2F\", \"Down\": \"#1976D2\"}\n\nsns.set_theme(style=\"ticks\", context=\"paper\", font_scale=1.1)\nfig, ax = plt.subplots(figsize=(8, 6))\n\nsns.scatterplot(data=df_de, x=\"log2fc\", y=\"neg_log10_p\",\n                hue=\"sig\", palette=palette,\n                alpha=0.6, s=18, linewidth=0, ax=ax)\n\n# Threshold lines\nax.axhline(-np.log10(padj_thresh), color=\"black\", linestyle=\"--\", linewidth=0.8)\nax.axvline( lfc_thresh,            color=\"black\", linestyle=\"--\", linewidth=0.8)\nax.axvline(-lfc_thresh,            color=\"black\", linestyle=\"--\", linewidth=0.8)\n\n# Label top 5 most significant genes per direction\nfor direction in [\"Up\", \"Down\"]:\n    top = df_de[df_de[\"sig\"] == direction].nlargest(5, \"neg_log10_p\")\n    for _, row in top.iterrows():\n        ax.text(row[\"log2fc\"], row[\"neg_log10_p\"] + 0.3, row[\"gene\"],\n                fontsize=6, ha=\"center\", va=\"bottom\",\n                color=palette[direction])\n\n# Annotation counts\nn_up   = (df_de[\"sig\"] == \"Up\").sum()\nn_down = (df_de[\"sig\"] == \"Down\").sum()\nax.set_title(f\"Volcano Plot  |  Up: {n_up}  Down: {n_down}\")\nax.set_xlabel(\"log2 Fold Change\")\nax.set_ylabel(\"-log10 p-value\")\nsns.despine(trim=True)\nplt.tight_layout()\nplt.savefig(\"volcano_plot.png\", dpi=300, bbox_inches=\"tight\")\nprint(f\"Volcano: {n_up} up, {n_down} down — saved volcano_plot.png\")\n```\n\n### Workflow 2: Multi-Condition Comparison with Grouped Violin + Strip Plots\n\n**Goal**: Compare gene expression (or any continuous measurement) across multiple treatments and time points, showing full distributions plus individual replicates.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(99)\ngenes    = [\"BRCA1\", \"TP53\", \"EGFR\"]\ntreats   = [\"DMSO\", \"Drug A\", \"Drug B\"]\ntimepoints = [\"6h\", \"24h\", \"48h\"]\nrows = []\nfor gene in genes:\n    base_expr = {\"BRCA1\": 7.5, \"TP53\": 6.2, \"EGFR\": 8.1}[gene]\n    for treat in treats:\n        treat_shift = {\"DMSO\": 0.0, \"Drug A\": -0.8, \"Drug B\": 0.6}[treat]\n        for tp in timepoints:\n            tp_shift = {\"6h\": 0.0, \"24h\": 0.3, \"48h\": 0.6}[tp]\n            for _ in range(12):\n                rows.append({\n                    \"gene\":      gene,\n                    \"treatment\": treat,\n                    \"timepoint\": tp,\n                    \"log2_expr\": base_expr + treat_shift + tp_shift + rng.normal(0, 0.5),\n                })\ndf_mc = pd.DataFrame(rows)\n\nsns.set_theme(style=\"whitegrid\", context=\"paper\", font_scale=1.0)\ng = sns.catplot(\n    data=df_mc,\n    x=\"timepoint\", y=\"log2_expr\",\n    hue=\"treatment\",\n    col=\"gene\",\n    kind=\"violin\",\n    inner=\"quart\",\n    dodge=True,\n    palette=\"Set2\",\n    height=4, aspect=0.9,\n    col_order=genes,\n    order=timepoints,\n)\n\n# Overlay individual points\nfor ax in g.axes.flat:\n    gene_label = ax.get_title()\n    gene_name  = gene_label.split(\" = \")[-1] if \" = \" in gene_label else gene_label\n    subset = df_mc[df_mc[\"gene\"] == gene_name]\n    sns.stripplot(\n        data=subset,\n        x=\"timepoint\", y=\"log2_expr\",\n        hue=\"treatment\",\n        dodge=True,\n        jitter=True,\n        size=2.5,\n        alpha=0.4,\n        palette=\"dark:black\",\n        order=timepoints,\n        legend=False,\n        ax=ax,\n    )\n\ng.set_axis_labels(\"Timepoint\", \"log2 Expression\")\ng.set_titles(\"{col_name}\")\ng.add_legend(title=\"Treatment\")\nsns.despine(trim=True)\ng.tight_layout()\ng.savefig(\"multigroup_violin.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved multigroup_violin.png\")\n```\n\n### Workflow 3: Pairwise Feature Exploration for Cell Morphology\n\n**Goal**: Quickly survey pairwise relationships in a multi-feature cell morphology dataset using `pairplot`, then examine one key pair with a `jointplot`.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(12)\nn_per_type = 80\ndf_morph = pd.DataFrame({\n    \"cell_area_um2\":    np.concatenate([rng.normal(320, 50, n_per_type),\n                                        rng.normal(420, 70, n_per_type),\n                                        rng.normal(280, 40, n_per_type)]),\n    \"nucleus_area_um2\": np.concatenate([rng.normal(85, 12, n_per_type),\n                                        rng.normal(110, 18, n_per_type),\n                                        rng.normal(75, 10, n_per_type)]),\n    \"eccentricity\":     np.abs(np.concatenate([rng.normal(0.6, 0.12, n_per_type),\n                                               rng.normal(0.8, 0.10, n_per_type),\n                                               rng.normal(0.5, 0.09, n_per_type)])),\n    \"mean_dapi\":        np.concatenate([rng.exponential(400, n_per_type),\n                                        rng.exponential(600, n_per_type),\n                                        rng.exponential(350, n_per_type)]),\n    \"cell_line\":        [\"HeLa\"] * n_per_type + [\"MCF7\"] * n_per_type + [\"U2OS\"] * n_per_type,\n})\n\n# 1. Pairplot survey\ng = sns.pairplot(df_morph, hue=\"cell_line\", corner=True,\n                 diag_kind=\"kde\", plot_kws={\"alpha\": 0.5, \"s\": 15},\n                 palette=\"Dark2\")\ng.savefig(\"morphology_pairplot.png\", dpi=150)\nprint(\"Saved morphology_pairplot.png\")\n\n# 2. Focused jointplot for the most informative pair\ng2 = sns.jointplot(data=df_morph, x=\"cell_area_um2\", y=\"nucleus_area_um2\",\n                   hue=\"cell_line\", kind=\"scatter\",\n                   marginal_kws={\"fill\": True, \"alpha\": 0.25},\n                   palette=\"Dark2\", alpha=0.6)\ng2.set_axis_labels(\"Cell Area (µm²)\", \"Nucleus Area (µm²)\")\ng2.savefig(\"morphology_jointplot.png\", dpi=150)\nprint(\"Saved morphology_jointplot.png\")\n```\n\n## Key Parameters\n\n| Parameter | Function(s) | Default | Range \u002F Options | Effect |\n|-----------|-------------|---------|-----------------|--------|\n| `hue` | All plot functions | `None` | Column name (categorical or continuous) | Color-encodes a variable; triggers automatic legend |\n| `style` | `scatterplot`, `lineplot` | `None` | Categorical column name | Encodes variable with marker shape or line dash pattern |\n| `size` | `scatterplot`, `lineplot` | `None` | Categorical or continuous column | Encodes variable via point or line size |\n| `col` \u002F `row` | Figure-level only (`relplot`, `displot`, `catplot`, `lmplot`) | `None` | Categorical column name | Creates one subplot panel per unique value |\n| `col_wrap` | Figure-level only | `None` | int | Wraps columns onto a new row after N panels |\n| `estimator` | `barplot`, `pointplot` | `\"mean\"` | `\"mean\"`, `\"median\"`, any callable | Aggregation function applied within each category |\n| `errorbar` | `barplot`, `lineplot`, `pointplot` | `(\"ci\", 95)` | `\"ci\"`, `\"sd\"`, `\"se\"`, `\"pi\"`, `None` | Error bar type displayed around the estimate |\n| `stat` | `histplot` | `\"count\"` | `\"count\"`, `\"frequency\"`, `\"density\"`, `\"probability\"` | Normalization applied to histogram bar heights |\n| `bw_adjust` | `kdeplot`, `violinplot` | `1.0` | `0.1`–`3.0` | KDE bandwidth multiplier; lower=spikier, higher=smoother |\n| `multiple` | `histplot`, `kdeplot` | `\"layer\"` | `\"layer\"`, `\"stack\"`, `\"dodge\"`, `\"fill\"` | How overlapping hue groups are drawn |\n| `inner` | `violinplot` | `\"box\"` | `\"box\"`, `\"quart\"`, `\"point\"`, `\"stick\"`, `None` | Interior annotation inside the violin body |\n| `standard_scale` | `clustermap` | `None` | `0` (rows), `1` (columns) | Z-score normalization axis before clustering |\n| `dodge` | `boxplot`, `violinplot`, `stripplot` | Varies | `True`, `False` | Separate hue-grouped elements along the axis |\n| `context` | `set_theme()` | `\"notebook\"` | `\"paper\"`, `\"notebook\"`, `\"talk\"`, `\"poster\"` | Scales font and line widths for output medium |\n\n## Best Practices\n\n1. **Prefer long-form DataFrames with named columns**: Seaborn's semantic mapping (`hue`, `style`, `size`) reads variable names directly from column names. Passing raw arrays loses axis labels and legends. Use `pd.melt()` to convert wide-form data.\n\n2. **Call `set_theme()` once at the top of a script**: This sets the global style, context, and palette for all subsequent plots, ensuring consistency. Reset to defaults with `sns.set_theme()`.\n   ```python\n   sns.set_theme(style=\"ticks\", context=\"paper\", font_scale=1.1,\n                 rc={\"axes.spines.right\": False, \"axes.spines.top\": False})\n   ```\n\n3. **Use axes-level functions for mixed-type custom layouts**: Figure-level functions (`relplot`, `catplot`) create their own figure and cannot be placed in an existing `Axes`. When combining different plot types (e.g., scatter + violin + heatmap), allocate a `plt.subplots()` grid and use axes-level functions with `ax=`.\n\n4. **Use colorblind-safe palettes**: `sns.set_palette(\"colorblind\")` or `palette=\"colorblind\"` produces a palette distinguishable by readers with common color vision deficiencies. For diverging data, use `\"RdBu_r\"` or `\"coolwarm\"` with `center=0`.\n\n5. **Overlay individual data points on summary plots**: Violin and bar plots hide distribution shape and sample size. Overlaying a `stripplot` or `swarmplot` with `alpha=0.4` and small `size` conveys data density without obscuring the summary statistic.\n\n6. **Size figure-level plots with `height` and `aspect`, not `figsize`**: Figure-level functions ignore `figsize`. Use `height=` (inches per panel) and `aspect=` (width-to-height ratio per panel). For axes-level, set `figsize` on the `plt.subplots()` call.\n\n7. **Anti-pattern — calling `plt.savefig()` on a figure-level grid**: Figure-level functions return a `FacetGrid`\u002F`JointGrid` object. Save it with `g.savefig(\"out.png\", dpi=300, bbox_inches=\"tight\")`, not `plt.savefig()`, which may capture a blank figure.\n\n## Common Recipes\n\n### Recipe: Publication-Ready Figure with Custom Palette and 300 DPI Export\n\nWhen to use: Preparing a multi-panel figure for journal submission or a slide deck.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nsns.set_theme(style=\"ticks\", context=\"paper\", font_scale=1.2,\n              rc={\"pdf.fonttype\": 42, \"ps.fonttype\": 42})\n\nrng = np.random.default_rng(7)\ndf = pd.DataFrame({\n    \"condition\": np.repeat([\"Control\", \"Treated\"], 40),\n    \"ki67_pct\":  np.concatenate([rng.normal(18, 4, 40), rng.normal(32, 6, 40)]),\n    \"apoptosis\": np.concatenate([rng.normal(5, 1.5, 40), rng.normal(12, 2.5, 40)]),\n})\n\ncustom_palette = {\"Control\": \"#4575B4\", \"Treated\": \"#D73027\"}\n\nfig, axes = plt.subplots(1, 2, figsize=(8, 4))\n\n# Panel A\nsns.boxplot(data=df, x=\"condition\", y=\"ki67_pct\",\n            palette=custom_palette, width=0.45, linewidth=1.2, ax=axes[0])\nsns.stripplot(data=df, x=\"condition\", y=\"ki67_pct\",\n              color=\"black\", alpha=0.35, size=3, jitter=True, ax=axes[0])\naxes[0].set_ylabel(\"Ki67 Positive Cells (%)\")\naxes[0].set_xlabel(\"\")\naxes[0].set_title(\"A\", loc=\"left\", fontweight=\"bold\")\n\n# Panel B\nsns.boxplot(data=df, x=\"condition\", y=\"apoptosis\",\n            palette=custom_palette, width=0.45, linewidth=1.2, ax=axes[1])\nsns.stripplot(data=df, x=\"condition\", y=\"apoptosis\",\n              color=\"black\", alpha=0.35, size=3, jitter=True, ax=axes[1])\naxes[1].set_ylabel(\"Apoptotic Cells (%)\")\naxes[1].set_xlabel(\"\")\naxes[1].set_title(\"B\", loc=\"left\", fontweight=\"bold\")\n\nsns.despine(trim=True)\nplt.tight_layout()\nplt.savefig(\"figure1.pdf\", dpi=300, bbox_inches=\"tight\")\nplt.savefig(\"figure1.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved figure1.pdf and figure1.png at 300 DPI\")\n```\n\n### Recipe: Clustered Heatmap with Row and Column Color Annotations\n\nWhen to use: Displaying a gene expression matrix with sample group annotations and hierarchical clustering to reveal co-expression modules.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(21)\nn_genes, n_samples = 40, 20\nconditions = [\"tumor\"] * 10 + [\"normal\"] * 10\n\n# Simulate expression: 3 co-expression modules\nexpr = pd.DataFrame(\n    rng.lognormal(2.5, 0.8, (n_genes, n_samples)),\n    index=[f\"GENE{i:03d}\" for i in range(n_genes)],\n    columns=[f\"{c[0].upper()}{i:02d}\" for i, c in enumerate(conditions)],\n)\n# Module 1: genes 0-13 up in tumor\nexpr.iloc[:14, :10]  *= 3.0\n# Module 2: genes 14-27 down in tumor\nexpr.iloc[14:28, :10] *= 0.3\n# Module 3: genes 28-39 unchanged\n\nlog_expr = np.log2(expr + 1)\n\n# Column colors: tumor=red, normal=blue\ncond_pal = {\"tumor\": \"#C62828\", \"normal\": \"#1565C0\"}\ncol_colors = [cond_pal[c] for c in conditions]\n\n# Row colors: module membership\nmodule_pal = {\"up\": \"#EF9A9A\", \"down\": \"#90CAF9\", \"stable\": \"#C8E6C9\"}\nrow_modules = ([\"up\"] * 14) + ([\"down\"] * 14) + ([\"stable\"] * 12)\nrow_colors  = [module_pal[m] for m in row_modules]\n\ng = sns.clustermap(\n    log_expr,\n    cmap=\"RdYlBu_r\",\n    center=log_expr.values.mean(),\n    standard_scale=0,           # z-score per gene (row)\n    method=\"ward\",\n    metric=\"euclidean\",\n    col_colors=col_colors,\n    row_colors=row_colors,\n    figsize=(14, 12),\n    linewidths=0,\n    cbar_pos=(0.02, 0.85, 0.03, 0.12),\n    cbar_kws={\"label\": \"Row z-score\"},\n    dendrogram_ratio=(0.12, 0.08),\n)\ng.ax_heatmap.set_xlabel(\"Sample\", fontsize=10)\ng.ax_heatmap.set_ylabel(\"Gene\",   fontsize=10)\ng.ax_heatmap.set_title(\"Gene Expression Clustermap\", fontsize=12, pad=80)\n\n# Manual legend for column\u002Frow annotations\nlegend_handles = [\n    mpatches.Patch(color=\"#C62828\", label=\"Tumor\"),\n    mpatches.Patch(color=\"#1565C0\", label=\"Normal\"),\n    mpatches.Patch(color=\"#EF9A9A\", label=\"Up in tumor\"),\n    mpatches.Patch(color=\"#90CAF9\", label=\"Down in tumor\"),\n    mpatches.Patch(color=\"#C8E6C9\", label=\"Stable\"),\n]\ng.ax_heatmap.legend(handles=legend_handles, bbox_to_anchor=(1.25, 1.05),\n                    loc=\"upper left\", frameon=False, fontsize=9)\n\nplt.savefig(\"clustermap_annotated.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved clustermap_annotated.png\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Legend placed outside plot, clipped in saved file | Figure-level functions place the legend outside by default | Add `bbox_inches=\"tight\"` to `savefig()`: `g.savefig(\"out.png\", dpi=300, bbox_inches=\"tight\")` |\n| `TypeError: FacetGrid.savefig()` or blank figure saved | Called `plt.savefig()` on a figure-level grid that owns its own figure | Use `g.savefig(...)` instead of `plt.savefig(...)` |\n| Overlapping x-axis category labels | Long label strings overlap at default rotation | Add `plt.xticks(rotation=45, ha=\"right\")` and `plt.tight_layout()` after the plot call |\n| `ValueError: Could not interpret value ... for parameter 'hue'` | Data is in wide-form; hue mapping requires long-form | Convert with `df.melt(id_vars=[...], var_name=\"sample\", value_name=\"expr\")` |\n| KDE bandwidth too smooth (loses bimodality) | Default `bw_adjust=1.0` over-smooths small datasets | Lower to `bw_adjust=0.5`; confirm peaks with `histplot` |\n| `clustermap` ignores `figsize` | Figure-level functions do not accept `figsize` as a kwarg in older seaborn | Pass `figsize` as a direct argument: `sns.clustermap(..., figsize=(12, 10))` |\n| Violin plot is a thin line (no shape) | Too few observations for KDE estimation | Switch to `kind=\"box\"` or `kind=\"strip\"`; or use `cut=0` to restrict KDE to data range |\n| Colors not distinguishable for many groups | Default palette repeats with >6 categories | Use `sns.color_palette(\"husl\", n_colors=N)` or `\"tab20\"` for up to 20 distinct colors |\n| Figure-level function ignores `ax=` parameter | Axes-level distinction: figure-level functions create their own figure | Use the corresponding axes-level function (`scatterplot`, `histplot`, etc.) with `ax=` |\n\n## Related Skills\n\n- **matplotlib-scientific-plotting** — low-level figure building, custom annotations, non-statistical plot types, and multi-panel layouts that mix seaborn with raw matplotlib\n- **plotly-interactive-plots** — interactive charts with hover, zoom, and HTML\u002FDash export\n- **pydeseq2-differential-expression** — produces the log2FC and p-values that feed into volcano-style scatter plots\n- **scikit-image-processing** — generates cell morphology measurements visualized with seaborn categorical\u002Fdistribution plots\n- **scientific-visualization** — decision guide for selecting the right chart type and color scheme before coding\n\n## References\n\n- [Seaborn official documentation](https:\u002F\u002Fseaborn.pydata.org\u002F) — API reference, tutorial, and gallery\n- [Seaborn example gallery](https:\u002F\u002Fseaborn.pydata.org\u002Fexamples\u002Findex.html) — visual index of all plot types\n- [Seaborn GitHub](https:\u002F\u002Fgithub.com\u002Fmwaskom\u002Fseaborn) — source code and issue tracker\n- Waskom ML (2021). \"seaborn: statistical data visualization.\" *Journal of Open Source Software*, 6(60), 3021. [https:\u002F\u002Fdoi.org\u002F10.21105\u002Fjoss.03021](https:\u002F\u002Fdoi.org\u002F10.21105\u002Fjoss.03021)\n","# Seaborn — Statistical Plots\n\n## Overview\n\nSeaborn is a Python library for statistical data visualization built on top of matplotlib. It works directly with pandas DataFrames, automatically handles grouping by categorical variables, computes confidence intervals and kernel density estimates, and produces attractive publication-ready figures with minimal configuration. Seaborn separates axes-level functions (embeddable in custom layouts) from figure-level functions (with built-in faceting), enabling both quick exploratory analysis and structured multi-panel figures.\n\n## When to Use\n\n- Comparing gene expression, protein abundance, or measurement distributions across experimental conditions (treatment vs. control, cell lines, time points)\n- Generating grouped box plots, violin plots, or strip plots to show both summary statistics and individual data points simultaneously\n- Visualizing pairwise correlations in multi-gene or multi-feature datasets as annotated heatmaps\n- Plotting regression fits with confidence bands between continuous variables (e.g., cell viability vs. drug concentration)\n- Faceting a single plot type across multiple sample subsets, tissue types, or experimental batches in one call\n- Rapid exploratory analysis of a new dataset using `pairplot` to survey all pairwise relationships at once\n- Use `matplotlib` directly when you need pixel-level control over figure elements, complex mixed-type layouts, or non-statistical custom plots\n- Use `plotly` when the output must be interactive (hover tooltips, zoom, pan) or embedded in a web application\n\n## Prerequisites\n\n- **Python packages**: `seaborn>=0.13`, `matplotlib`, `pandas`, `numpy`\n- **Data requirements**: Pandas DataFrame in long-form (tidy) format; each observation is a row, each variable is a column\n- **Environment**: Standard Python environment; no GPU or special hardware required\n\n```bash\npip install \"seaborn>=0.13\" matplotlib pandas numpy scipy\n```\n\n## Quick Start\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n# Simulate gene expression across conditions\nrng = np.random.default_rng(42)\ndf = pd.DataFrame({\n    \"gene\":      [\"BRCA1\"] * 60 + [\"TP53\"] * 60,\n    \"condition\": [\"control\", \"treated\"] * 60,\n    \"log2_expr\": np.concatenate([\n        rng.normal(5.2, 0.8, 60),\n        rng.normal(6.1, 0.9, 60),\n    ])\n})\n\nsns.set_theme(style=\"ticks\", context=\"notebook\")\nsns.boxplot(data=df, x=\"gene\", y=\"log2_expr\", hue=\"condition\", palette=\"Set2\")\nplt.ylabel(\"log2 Expression\")\nplt.title(\"Gene Expression by Condition\")\nplt.tight_layout()\nplt.savefig(\"quickstart_boxplot.png\", dpi=150)\nprint(\"Saved quickstart_boxplot.png\")\n```\n\n## Core API\n\n### 1. Distribution Plots\n\nVisualize univariate distributions and compare them across groups. `histplot` bins data; `kdeplot` fits a smooth density estimate; `displot` is the figure-level wrapper that adds faceting.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(0)\nn = 200\ndf = pd.DataFrame({\n    \"log2_tpm\":  np.concatenate([rng.normal(4.5, 1.1, n), rng.normal(6.0, 1.3, n)]),\n    \"sample\":    [\"tumor\"] * n + [\"normal\"] * n,\n})\n\nfig, axes = plt.subplots(1, 3, figsize=(15, 4))\n\n# Histogram with density normalization and stacked hue groups\nsns.histplot(data=df, x=\"log2_tpm\", hue=\"sample\", stat=\"density\",\n             multiple=\"stack\", bins=30, ax=axes[0])\naxes[0].set_title(\"Histogram (stacked)\")\n\n# KDE with fill — bandwidth controlled by bw_adjust\nsns.kdeplot(data=df, x=\"log2_tpm\", hue=\"sample\", fill=True,\n            bw_adjust=0.8, alpha=0.4, ax=axes[1])\naxes[1].set_title(\"KDE (filled)\")\n\n# ECDF — useful for comparing cumulative distributions\nsns.ecdfplot(data=df, x=\"log2_tpm\", hue=\"sample\", ax=axes[2])\naxes[2].set_title(\"ECDF\")\n\nplt.tight_layout()\nplt.savefig(\"distributions.png\", dpi=150)\nprint(\"Saved distributions.png\")\n```\n\n```python\n# Bivariate KDE: joint distribution of two continuous variables\nrng = np.random.default_rng(1)\ndf2 = pd.DataFrame({\n    \"log2_rna\": rng.normal(5.5, 1.2, 300),\n    \"log2_prot\": rng.normal(4.8, 1.0, 300) + 0.6 * rng.normal(5.5, 1.2, 300),\n})\nsns.kdeplot(data=df2, x=\"log2_rna\", y=\"log2_prot\",\n            fill=True, levels=8, thresh=0.05, cmap=\"Blues\")\nplt.xlabel(\"log2 RNA (TPM)\")\nplt.ylabel(\"log2 Protein (iBAQ)\")\nplt.title(\"RNA–Protein Correlation Density\")\nplt.tight_layout()\nplt.savefig(\"bivariate_kde.png\", dpi=150)\nprint(\"Saved bivariate_kde.png\")\n```\n\n### 2. Categorical Plots\n\nCompare distributions or aggregated statistics across categorical groups. Axes-level functions (`boxplot`, `violinplot`, `stripplot`, `swarmplot`, `barplot`) accept an `ax=` parameter for embedding in custom layouts.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(2)\nconditions = [\"DMSO\", \"Drug A 1uM\", \"Drug A 10uM\", \"Drug B 1uM\", \"Drug B 10uM\"]\ndf = pd.DataFrame({\n    \"condition\": np.repeat(conditions, 30),\n    \"viability\": np.concatenate([\n        rng.normal(100, 5, 30),\n        rng.normal(92, 7, 30),\n        rng.normal(65, 10, 30),\n        rng.normal(88, 8, 30),\n        rng.normal(45, 12, 30),\n    ])\n})\n\nfig, axes = plt.subplots(1, 3, figsize=(18, 5))\n\n# Box plot — shows quartiles and outliers\nsns.boxplot(data=df, x=\"condition\", y=\"viability\",\n            palette=\"husl\", width=0.5, ax=axes[0])\naxes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=30, ha=\"right\")\naxes[0].set_title(\"Box Plot\")\n\n# Violin — KDE shape + inner quartile lines\nsns.violinplot(data=df, x=\"condition\", y=\"viability\",\n               inner=\"quart\", palette=\"muted\", ax=axes[1])\naxes[1].set_xticklabels(axes[1].get_xticklabels(), rotation=30, ha=\"right\")\naxes[1].set_title(\"Violin Plot\")\n\n# Strip plot overlaid on box — shows all individual points\nsns.boxplot(data=df, x=\"condition\", y=\"viability\",\n            palette=\"pastel\", width=0.5, ax=axes[2])\nsns.stripplot(data=df, x=\"condition\", y=\"viability\",\n              color=\"black\", alpha=0.4, size=3, jitter=True, ax=axes[2])\naxes[2].set_xticklabels(axes[2].get_xticklabels(), rotation=30, ha=\"right\")\naxes[2].set_title(\"Box + Strip\")\n\nplt.tight_layout()\nplt.savefig(\"categorical.png\", dpi=150)\nprint(\"Saved categorical.png\")\n```\n\n```python\n# Bar plot with mean ± 95% CI and individual points (swarm)\nfig, ax = plt.subplots(figsize=(8, 5))\nsns.barplot(data=df, x=\"condition\", y=\"viability\",\n            estimator=\"mean\", errorbar=\"ci\", palette=\"Set3\", ax=ax)\nsns.swarmplot(data=df, x=\"condition\", y=\"viability\",\n              color=\"black\", size=3, alpha=0.5, ax=ax)\nax.set_ylabel(\"Cell Viability (%)\")\nax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha=\"right\")\nplt.tight_layout()\nplt.savefig(\"barswarm.png\", dpi=150)\nprint(\"Saved barswarm.png\")\n```\n\n### 3. Relational Plots\n\nVisualize relationships between continuous variables. `scatterplot` and `lineplot` are axes-level; `relplot` is the figure-level wrapper that supports `col` and `row` faceting.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(3)\nn = 150\ndf = pd.DataFrame({\n    \"molecular_weight\": rng.uniform(200, 800, n),\n    \"logP\":             rng.uniform(-2, 6, n),\n    \"pIC50\":            rng.normal(6.5, 1.2, n),\n    \"target_class\":     rng.choice([\"kinase\", \"GPCR\", \"protease\"], n),\n    \"pass_lipinski\":    rng.choice([\"yes\", \"no\"], n, p=[0.7, 0.3]),\n})\n\n# Scatter with hue (categorical color) + size (continuous) + style (marker)\nsns.scatterplot(data=df, x=\"molecular_weight\", y=\"pIC50\",\n                hue=\"target_class\", size=\"logP\", style=\"pass_lipinski\",\n                sizes=(30, 120), alpha=0.7)\nplt.xlabel(\"Molecular Weight (Da)\")\nplt.ylabel(\"pIC50\")\nplt.title(\"Compound Bioactivity by Target Class\")\nplt.tight_layout()\nplt.savefig(\"relational_scatter.png\", dpi=150)\nprint(\"Saved relational_scatter.png\")\n```\n\n```python\n# Line plot with automatic mean aggregation and SD error band across replicates\ntimepoints = [0, 1, 2, 4, 8, 24]\ngroups = [\"untreated\", \"low_dose\", \"high_dose\"]\nrows = []\nfor grp, base in zip(groups, [100.0, 95.0, 80.0]):\n    for tp in timepoints:\n        for _ in range(5):  # 5 replicates\n            rows.append({\"timepoint_h\": tp, \"group\": grp,\n                         \"confluency\": base * np.exp(-0.02 * tp * (1 + rng.normal(0, 0.1)))})\ntime_df = pd.DataFrame(rows)\n\nsns.lineplot(data=time_df, x=\"timepoint_h\", y=\"confluency\",\n             hue=\"group\", style=\"group\", errorbar=\"sd\", markers=True, dashes=False)\nplt.xlabel(\"Time (h)\")\nplt.ylabel(\"Confluency (%)\")\nplt.title(\"Cell Growth Inhibition (mean ± SD, n=5)\")\nplt.tight_layout()\nplt.savefig(\"lineplot.png\", dpi=150)\nprint(\"Saved lineplot.png\")\n```\n\n### 4. Regression Plots\n\nFit linear (or polynomial\u002Flowess) models and visualize them with confidence bands. `regplot` is axes-level; `lmplot` is figure-level with faceting support.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(4)\nn = 120\ntumor_size = rng.uniform(0.5, 6.0, n)\nsurvival_months = 40 - 5 * tumor_size + rng.normal(0, 4, n)\ngrade = rng.choice([\"low\", \"high\"], n, p=[0.5, 0.5])\ndf = pd.DataFrame({\"tumor_size_cm\": tumor_size,\n                   \"survival_months\": survival_months,\n                   \"grade\": grade})\n\nfig, axes = plt.subplots(1, 2, figsize=(13, 5))\n\n# Linear regression with 95% CI band\nsns.regplot(data=df, x=\"tumor_size_cm\", y=\"survival_months\",\n            ci=95, scatter_kws={\"alpha\": 0.4, \"s\": 25}, ax=axes[0])\naxes[0].set_title(\"Linear Regression (95% CI)\")\n\n# Residuals plot — check for homoscedasticity\nsns.residplot(data=df, x=\"tumor_size_cm\", y=\"survival_months\",\n              scatter_kws={\"alpha\": 0.4, \"s\": 25}, ax=axes[1])\naxes[1].axhline(0, color=\"red\", linestyle=\"--\", linewidth=1)\naxes[1].set_title(\"Residuals vs Fitted\")\n\nplt.tight_layout()\nplt.savefig(\"regression.png\", dpi=150)\nprint(\"Saved regression.png\")\n```\n\n```python\n# lmplot — figure-level: separate regression lines per grade (hue) + facets\ng = sns.lmplot(data=df, x=\"tumor_size_cm\", y=\"survival_months\",\n               hue=\"grade\", col=\"grade\", ci=95,\n               scatter_kws={\"alpha\": 0.4}, height=4, aspect=1.1)\ng.set_axis_labels(\"Tumor Size (cm)\", \"Survival (months)\")\ng.set_titles(\"{col_name} grade\")\ng.savefig(\"lmplot_faceted.png\", dpi=150)\nprint(\"Saved lmplot_faceted.png\")\n```\n\n### 5. Matrix Plots\n\nVisualize rectangular data as color-encoded matrices. `heatmap` is axes-level; `clustermap` is figure-level and applies hierarchical clustering to rows and columns.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(5)\ngenes = [f\"GENE{i}\" for i in range(1, 9)]\nsamples = [f\"S{i}\" for i in range(1, 7)]\n\n# Simulate log2 fold-change matrix (rows=genes, cols=samples)\nlfc = pd.DataFrame(\n    rng.normal(0, 1.5, size=(8, 6)),\n    index=genes, columns=samples\n)\n# Inject a pattern: first 3 genes up in samples 1-3, down in 4-6\nlfc.iloc[:3, :3] += 2.5\nlfc.iloc[:3, 3:] -= 2.5\n\n# Correlation heatmap of numeric features\ndf_num = pd.DataFrame(\n    rng.standard_normal((80, 5)),\n    columns=[\"GeneA\", \"GeneB\", \"GeneC\", \"GeneD\", \"GeneE\"]\n)\ndf_num[\"GeneB\"] = df_num[\"GeneA\"] * 0.85 + rng.normal(0, 0.3, 80)\ncorr = df_num.corr()\n\nfig, axes = plt.subplots(1, 2, figsize=(14, 5))\n\nsns.heatmap(corr, annot=True, fmt=\".2f\", cmap=\"coolwarm\",\n            center=0, square=True, linewidths=0.5, ax=axes[0])\naxes[0].set_title(\"Pearson Correlation Heatmap\")\n\nsns.heatmap(lfc, cmap=\"RdBu_r\", center=0, annot=True, fmt=\".1f\",\n            linewidths=0.3, cbar_kws={\"label\": \"log2FC\"}, ax=axes[1])\naxes[1].set_title(\"log2 Fold Change Matrix\")\n\nplt.tight_layout()\nplt.savefig(\"heatmaps.png\", dpi=150)\nprint(\"Saved heatmaps.png\")\n```\n\n```python\n# Clustermap with hierarchical clustering and row\u002Fcolumn color annotations\nrng = np.random.default_rng(6)\nn_genes, n_samples = 30, 16\nexpr = pd.DataFrame(\n    rng.lognormal(mean=2.0, sigma=1.2, size=(n_genes, n_samples)),\n    index=[f\"GENE{i:03d}\" for i in range(n_genes)],\n    columns=[f\"{'T' if i \u003C 8 else 'N'}{i:02d}\" for i in range(n_samples)]\n)\n\n# Column annotation colors (tumor vs normal)\ncol_colors = [\"#D32F2F\" if c.startswith(\"T\") else \"#1976D2\" for c in expr.columns]\n\ng = sns.clustermap(\n    np.log2(expr + 1),\n    cmap=\"viridis\",\n    standard_scale=0,          # z-score across rows (genes)\n    method=\"ward\",\n    metric=\"euclidean\",\n    col_colors=col_colors,\n    figsize=(12, 10),\n    linewidths=0,\n    cbar_pos=(0.02, 0.8, 0.03, 0.15),\n    cbar_kws={\"label\": \"Row z-score\"},\n)\ng.ax_heatmap.set_xlabel(\"Sample\")\ng.ax_heatmap.set_ylabel(\"Gene\")\nplt.savefig(\"clustermap.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved clustermap.png\")\n```\n\n### 6. Multi-Variable Grids\n\nSurvey all pairwise relationships with `pairplot` or display a bivariate distribution with marginals using `jointplot`. For fully custom grid layouts, use `FacetGrid` directly.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(7)\nn = 60\ndf = pd.DataFrame({\n    \"cell_area\":      rng.normal(350, 60, n * 3),\n    \"nucleus_area\":   rng.normal(90, 15, n * 3),\n    \"mean_intensity\": rng.exponential(500, n * 3),\n    \"aspect_ratio\":   np.abs(rng.normal(1.3, 0.3, n * 3)),\n    \"cell_type\":      ([\"HeLa\"] * n + [\"MCF7\"] * n + [\"A549\"] * n),\n})\n\n# Pairplot — matrix of pairwise scatter + KDE on diagonal\ng = sns.pairplot(df, hue=\"cell_type\", corner=True,\n                 diag_kind=\"kde\", plot_kws={\"alpha\": 0.5, \"s\": 20})\ng.savefig(\"pairplot.png\", dpi=150)\nprint(\"Saved pairplot.png\")\n```\n\n```python\n# Jointplot — bivariate KDE with marginal histograms\ng = sns.jointplot(data=df, x=\"cell_area\", y=\"nucleus_area\",\n                  hue=\"cell_type\", kind=\"scatter\",\n                  marginal_kws={\"fill\": True, \"alpha\": 0.3})\ng.set_axis_labels(\"Cell Area (µm²)\", \"Nucleus Area (µm²)\")\ng.savefig(\"jointplot.png\", dpi=150)\nprint(\"Saved jointplot.png\")\n```\n\n```python\n# FacetGrid — custom layout: KDE of mean_intensity per cell type\ng = sns.FacetGrid(df, col=\"cell_type\", height=3.5, aspect=1.1,\n                  sharey=False)\ng.map(sns.histplot, \"mean_intensity\", bins=20, kde=True, color=\"steelblue\")\ng.set_axis_labels(\"Mean Intensity (AU)\", \"Count\")\ng.set_titles(\"{col_name}\")\ng.tight_layout()\ng.savefig(\"facetgrid_intensity.png\", dpi=150)\nprint(\"Saved facetgrid_intensity.png\")\n```\n\n## Key Concepts\n\n### Figure-Level vs Axes-Level Functions\n\nSeaborn has two tiers of functions with different return types and composability:\n\n| Feature | Axes-Level | Figure-Level |\n|---------|-----------|--------------|\n| **Examples** | `scatterplot`, `histplot`, `boxplot`, `heatmap`, `regplot` | `relplot`, `displot`, `catplot`, `lmplot` |\n| **Returns** | `matplotlib.axes.Axes` | `FacetGrid` \u002F `JointGrid` \u002F `PairGrid` |\n| **Faceting** | Manual (create subplots yourself) | Built-in (`col=`, `row=` params) |\n| **Sizing** | `figsize=` on parent figure | `height=` + `aspect=` per facet panel |\n| **Placement** | `ax=` parameter | Cannot be placed in an existing axes |\n| **Saving** | `plt.savefig(...)` | `g.savefig(...)` |\n| **Use when** | Combining different plot types in one figure | Quick multi-panel exploratory views |\n\n```python\n# Axes-level: place in a pre-allocated subplot grid\nfig, axes = plt.subplots(1, 2, figsize=(12, 5))\nsns.violinplot(data=df, x=\"cell_type\", y=\"cell_area\", ax=axes[0])\nsns.scatterplot(data=df, x=\"cell_area\", y=\"nucleus_area\", hue=\"cell_type\", ax=axes[1])\n```\n\n### Long-Form vs Wide-Form Data\n\nSeaborn semantic mappings (`hue`, `size`, `style`) require **long-form (tidy) data** where each variable is a column and each observation is a row. Some functions (`heatmap`, `clustermap`, `lineplot`) also accept wide-form.\n\n```python\n# Wide-form: unsuitable for hue\u002Fstyle mappings\n#   sample_A  sample_B  sample_C\n# 0      5.1       6.2       4.8\n\n# Long-form (preferred): melt wide → long\nwide = pd.DataFrame({\"sampleA\": [5.1, 4.3], \"sampleB\": [6.2, 5.9]})\nlong = wide.melt(var_name=\"sample\", value_name=\"log2_expr\")\n# → columns: sample, log2_expr\n```\n\n## Common Workflows\n\n### Workflow 1: Differential Expression Scatter with Significance Thresholds\n\n**Goal**: Visualize log2 fold-change vs -log10 p-value (volcano-style) with significance annotations, colored by regulation status, and labeled top hits.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(42)\nn = 500\nlfc   = rng.normal(0, 1.5, n)\npvals = 10 ** (-rng.exponential(1.5, n))        # skewed toward low significance\npvals = np.clip(pvals, 1e-20, 1.0)\ngenes = [f\"GENE{i:04d}\" for i in range(n)]\n\ndf_de = pd.DataFrame({\"gene\": genes, \"log2fc\": lfc, \"pvalue\": pvals})\ndf_de[\"neg_log10_p\"] = -np.log10(df_de[\"pvalue\"])\n\n# Classify regulation status\nlfc_thresh = 1.0\npadj_thresh = 0.05\ndf_de[\"sig\"] = \"NS\"\ndf_de.loc[(df_de[\"log2fc\"] >  lfc_thresh) & (df_de[\"pvalue\"] \u003C padj_thresh), \"sig\"] = \"Up\"\ndf_de.loc[(df_de[\"log2fc\"] \u003C -lfc_thresh) & (df_de[\"pvalue\"] \u003C padj_thresh), \"sig\"] = \"Down\"\n\npalette = {\"NS\": \"#AAAAAA\", \"Up\": \"#D32F2F\", \"Down\": \"#1976D2\"}\n\nsns.set_theme(style=\"ticks\", context=\"paper\", font_scale=1.1)\nfig, ax = plt.subplots(figsize=(8, 6))\n\nsns.scatterplot(data=df_de, x=\"log2fc\", y=\"neg_log10_p\",\n                hue=\"sig\", palette=palette,\n                alpha=0.6, s=18, linewidth=0, ax=ax)\n\n# Threshold lines\nax.axhline(-np.log10(padj_thresh), color=\"black\", linestyle=\"--\", linewidth=0.8)\nax.axvline( lfc_thresh,            color=\"black\", linestyle=\"--\", linewidth=0.8)\nax.axvline(-lfc_thresh,            color=\"black\", linestyle=\"--\", linewidth=0.8)\n\n# Label top 5 most significant genes per direction\nfor direction in [\"Up\", \"Down\"]:\n    top = df_de[df_de[\"sig\"] == direction].nlargest(5, \"neg_log10_p\")\n    for _, row in top.iterrows():\n        ax.text(row[\"log2fc\"], row[\"neg_log10_p\"] + 0.3, row[\"gene\"],\n                fontsize=6, ha=\"center\", va=\"bottom\",\n                color=palette[direction])\n\n# Annotation counts\nn_up   = (df_de[\"sig\"] == \"Up\").sum()\nn_down = (df_de[\"sig\"] == \"Down\").sum()\nax.set_title(f\"Volcano Plot  |  Up: {n_up}  Down: {n_down}\")\nax.set_xlabel(\"log2 Fold Change\")\nax.set_ylabel(\"-log10 p-value\")\nsns.despine(trim=True)\nplt.tight_layout()\nplt.savefig(\"volcano_plot.png\", dpi=300, bbox_inches=\"tight\")\nprint(f\"Volcano: {n_up} up, {n_down} down — saved volcano_plot.png\")\n```\n\n### Workflow 2: Multi-Condition Comparison with Grouped Violin + Strip Plots\n\n**Goal**: Compare gene expression (or any continuous measurement) across multiple treatments and time points, showing full distributions plus individual replicates.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(99)\ngenes    = [\"BRCA1\", \"TP53\", \"EGFR\"]\ntreats   = [\"DMSO\", \"Drug A\", \"Drug B\"]\ntimepoints = [\"6h\", \"24h\", \"48h\"]\nrows = []\nfor gene in genes:\n    base_expr = {\"BRCA1\": 7.5, \"TP53\": 6.2, \"EGFR\": 8.1}[gene]\n    for treat in treats:\n        treat_shift = {\"DMSO\": 0.0, \"Drug A\": -0.8, \"Drug B\": 0.6}[treat]\n        for tp in timepoints:\n            tp_shift = {\"6h\": 0.0, \"24h\": 0.3, \"48h\": 0.6}[tp]\n            for _ in range(12):\n                rows.append({\n                    \"gene\":      gene,\n                    \"treatment\": treat,\n                    \"timepoint\": tp,\n                    \"log2_expr\": base_expr + treat_shift + tp_shift + rng.normal(0, 0.5),\n                })\ndf_mc = pd.DataFrame(rows)\n\nsns.set_theme(style=\"whitegrid\", context=\"paper\", font_scale=1.0)\ng = sns.catplot(\n    data=df_mc,\n    x=\"timepoint\", y=\"log2_expr\",\n    hue=\"treatment\",\n    col=\"gene\",\n    kind=\"violin\",\n    inner=\"quart\",\n    dodge=True,\n    palette=\"Set2\",\n    height=4, aspect=0.9,\n    col_order=genes,\n    order=timepoints,\n)\n\n# Overlay individual points\nfor ax in g.axes.flat:\n    gene_label = ax.get_title()\n    gene_name  = gene_label.split(\" = \")[-1] if \" = \" in gene_label else gene_label\n    subset = df_mc[df_mc[\"gene\"] == gene_name]\n    sns.stripplot(\n        data=subset,\n        x=\"timepoint\", y=\"log2_expr\",\n        hue=\"treatment\",\n        dodge=True,\n        jitter=True,\n        size=2.5,\n        alpha=0.4,\n        palette=\"dark:black\",\n        order=timepoints,\n        legend=False,\n        ax=ax,\n    )\n\ng.set_axis_labels(\"Timepoint\", \"log2 Expression\")\ng.set_titles(\"{col_name}\")\ng.add_legend(title=\"Treatment\")\nsns.despine(trim=True)\ng.tight_layout()\ng.savefig(\"multigroup_violin.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved multigroup_violin.png\")\n```\n\n### Workflow 3: Pairwise Feature Exploration for Cell Morphology\n\n**Goal**: Quickly survey pairwise relationships in a multi-feature cell morphology dataset using `pairplot`, then examine one key pair with a `jointplot`.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(12)\nn_per_type = 80\ndf_morph = pd.DataFrame({\n    \"cell_area_um2\":    np.concatenate([rng.normal(320, 50, n_per_type),\n                                        rng.normal(420, 70, n_per_type),\n                                        rng.normal(280, 40, n_per_type)]),\n    \"nucleus_area_um2\": np.concatenate([rng.normal(85, 12, n_per_type),\n                                        rng.normal(110, 18, n_per_type),\n                                        rng.normal(75, 10, n_per_type)]),\n    \"eccentricity\":     np.abs(np.concatenate([rng.normal(0.6, 0.12, n_per_type),\n                                               rng.normal(0.8, 0.10, n_per_type),\n                                               rng.normal(0.5, 0.09, n_per_type)])),\n    \"mean_dapi\":        np.concatenate([rng.exponential(400, n_per_type),\n                                        rng.exponential(600, n_per_type),\n                                        rng.exponential(350, n_per_type)]),\n    \"cell_line\":        [\"HeLa\"] * n_per_type + [\"MCF7\"] * n_per_type + [\"U2OS\"] * n_per_type,\n})\n\n# 1. Pairplot survey\ng = sns.pairplot(df_morph, hue=\"cell_line\", corner=True,\n                 diag_kind=\"kde\", plot_kws={\"alpha\": 0.5, \"s\": 15},\n                 palette=\"Dark2\")\ng.savefig(\"morphology_pairplot.png\", dpi=150)\nprint(\"Saved morphology_pairplot.png\")\n\n# 2. Focused jointplot for the most informative pair\ng2 = sns.jointplot(data=df_morph, x=\"cell_area_um2\", y=\"nucleus_area_um2\",\n                   hue=\"cell_line\", kind=\"scatter\",\n                   marginal_kws={\"fill\": True, \"alpha\": 0.25},\n                   palette=\"Dark2\", alpha=0.6)\ng2.set_axis_labels(\"Cell Area (µm²)\", \"Nucleus Area (µm²)\")\ng2.savefig(\"morphology_jointplot.png\", dpi=150)\nprint(\"Saved morphology_jointplot.png\")\n```\n\n## Key Parameters\n\n| Parameter | Function(s) | Default | Range \u002F Options | Effect |\n|-----------|-------------|---------|-----------------|--------|\n| `hue` | All plot functions | `None` | Column name (categorical or continuous) | Color-encodes a variable; triggers automatic legend |\n| `style` | `scatterplot`, `lineplot` | `None` | Categorical column name | Encodes variable with marker shape or line dash pattern |\n| `size` | `scatterplot`, `lineplot` | `None` | Categorical or continuous column | Encodes variable via point or line size |\n| `col` \u002F `row` | Figure-level only (`relplot`, `displot`, `catplot`, `lmplot`) | `None` | Categorical column name | Creates one subplot panel per unique value |\n| `col_wrap` | Figure-level only | `None` | int | Wraps columns onto a new row after N panels |\n| `estimator` | `barplot`, `pointplot` | `\"mean\"` | `\"mean\"`, `\"median\"`, any callable | Aggregation function applied within each category |\n| `errorbar` | `barplot`, `lineplot`, `pointplot` | `(\"ci\", 95)` | `\"ci\"`, `\"sd\"`, `\"se\"`, `\"pi\"`, `None` | Error bar type displayed around the estimate |\n| `stat` | `histplot` | `\"count\"` | `\"count\"`, `\"frequency\"`, `\"density\"`, `\"probability\"` | Normalization applied to histogram bar heights |\n| `bw_adjust` | `kdeplot`, `violinplot` | `1.0` | `0.1`–`3.0` | KDE bandwidth multiplier; lower=spikier, higher=smoother |\n| `multiple` | `histplot`, `kdeplot` | `\"layer\"` | `\"layer\"`, `\"stack\"`, `\"dodge\"`, `\"fill\"` | How overlapping hue groups are drawn |\n| `inner` | `violinplot` | `\"box\"` | `\"box\"`, `\"quart\"`, `\"point\"`, `\"stick\"`, `None` | Interior annotation inside the violin body |\n| `standard_scale` | `clustermap` | `None` | `0` (rows), `1` (columns) | Z-score normalization axis before clustering |\n| `dodge` | `boxplot`, `violinplot`, `stripplot` | Varies | `True`, `False` | Separate hue-grouped elements along the axis |\n| `context` | `set_theme()` | `\"notebook\"` | `\"paper\"`, `\"notebook\"`, `\"talk\"`, `\"poster\"` | Scales font and line widths for output medium |\n\n## Best Practices\n\n1. **Prefer long-form DataFrames with named columns**: Seaborn's semantic mapping (`hue`, `style`, `size`) reads variable names directly from column names. Passing raw arrays loses axis labels and legends. Use `pd.melt()` to convert wide-form data.\n\n2. **Call `set_theme()` once at the top of a script**: This sets the global style, context, and palette for all subsequent plots, ensuring consistency. Reset to defaults with `sns.set_theme()`.\n   ```python\n   sns.set_theme(style=\"ticks\", context=\"paper\", font_scale=1.1,\n                 rc={\"axes.spines.right\": False, \"axes.spines.top\": False})\n   ```\n\n3. **Use axes-level functions for mixed-type custom layouts**: Figure-level functions (`relplot`, `catplot`) create their own figure and cannot be placed in an existing `Axes`. When combining different plot types (e.g., scatter + violin + heatmap), allocate a `plt.subplots()` grid and use axes-level functions with `ax=`.\n\n4. **Use colorblind-safe palettes**: `sns.set_palette(\"colorblind\")` or `palette=\"colorblind\"` produces a palette distinguishable by readers with common color vision deficiencies. For diverging data, use `\"RdBu_r\"` or `\"coolwarm\"` with `center=0`.\n\n5. **Overlay individual data points on summary plots**: Violin and bar plots hide distribution shape and sample size. Overlaying a `stripplot` or `swarmplot` with `alpha=0.4` and small `size` conveys data density without obscuring the summary statistic.\n\n6. **Size figure-level plots with `height` and `aspect`, not `figsize`**: Figure-level functions ignore `figsize`. Use `height=` (inches per panel) and `aspect=` (width-to-height ratio per panel). For axes-level, set `figsize` on the `plt.subplots()` call.\n\n7. **Anti-pattern — calling `plt.savefig()` on a figure-level grid**: Figure-level functions return a `FacetGrid`\u002F`JointGrid` object. Save it with `g.savefig(\"out.png\", dpi=300, bbox_inches=\"tight\")`, not `plt.savefig()`, which may capture a blank figure.\n\n## Common Recipes\n\n### Recipe: Publication-Ready Figure with Custom Palette and 300 DPI Export\n\nWhen to use: Preparing a multi-panel figure for journal submission or a slide deck.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nsns.set_theme(style=\"ticks\", context=\"paper\", font_scale=1.2,\n              rc={\"pdf.fonttype\": 42, \"ps.fonttype\": 42})\n\nrng = np.random.default_rng(7)\ndf = pd.DataFrame({\n    \"condition\": np.repeat([\"Control\", \"Treated\"], 40),\n    \"ki67_pct\":  np.concatenate([rng.normal(18, 4, 40), rng.normal(32, 6, 40)]),\n    \"apoptosis\": np.concatenate([rng.normal(5, 1.5, 40), rng.normal(12, 2.5, 40)]),\n})\n\ncustom_palette = {\"Control\": \"#4575B4\", \"Treated\": \"#D73027\"}\n\nfig, axes = plt.subplots(1, 2, figsize=(8, 4))\n\n# Panel A\nsns.boxplot(data=df, x=\"condition\", y=\"ki67_pct\",\n            palette=custom_palette, width=0.45, linewidth=1.2, ax=axes[0])\nsns.stripplot(data=df, x=\"condition\", y=\"ki67_pct\",\n              color=\"black\", alpha=0.35, size=3, jitter=True, ax=axes[0])\naxes[0].set_ylabel(\"Ki67 Positive Cells (%)\")\naxes[0].set_xlabel(\"\")\naxes[0].set_title(\"A\", loc=\"left\", fontweight=\"bold\")\n\n# Panel B\nsns.boxplot(data=df, x=\"condition\", y=\"apoptosis\",\n            palette=custom_palette, width=0.45, linewidth=1.2, ax=axes[1])\nsns.stripplot(data=df, x=\"condition\", y=\"apoptosis\",\n              color=\"black\", alpha=0.35, size=3, jitter=True, ax=axes[1])\naxes[1].set_ylabel(\"Apoptotic Cells (%)\")\naxes[1].set_xlabel(\"\")\naxes[1].set_title(\"B\", loc=\"left\", fontweight=\"bold\")\n\nsns.despine(trim=True)\nplt.tight_layout()\nplt.savefig(\"figure1.pdf\", dpi=300, bbox_inches=\"tight\")\nplt.savefig(\"figure1.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved figure1.pdf and figure1.png at 300 DPI\")\n```\n\n### Recipe: Clustered Heatmap with Row and Column Color Annotations\n\nWhen to use: Displaying a gene expression matrix with sample group annotations and hierarchical clustering to reveal co-expression modules.\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport pandas as pd\n\nrng = np.random.default_rng(21)\nn_genes, n_samples = 40, 20\nconditions = [\"tumor\"] * 10 + [\"normal\"] * 10\n\n# Simulate expression: 3 co-expression modules\nexpr = pd.DataFrame(\n    rng.lognormal(2.5, 0.8, (n_genes, n_samples)),\n    index=[f\"GENE{i:03d}\" for i in range(n_genes)],\n    columns=[f\"{c[0].upper()}{i:02d}\" for i, c in enumerate(conditions)],\n)\n# Module 1: genes 0-13 up in tumor\nexpr.iloc[:14, :10]  *= 3.0\n# Module 2: genes 14-27 down in tumor\nexpr.iloc[14:28, :10] *= 0.3\n# Module 3: genes 28-39 unchanged\n\nlog_expr = np.log2(expr + 1)\n\n# Column colors: tumor=red, normal=blue\ncond_pal = {\"tumor\": \"#C62828\", \"normal\": \"#1565C0\"}\ncol_colors = [cond_pal[c] for c in conditions]\n\n# Row colors: module membership\nmodule_pal = {\"up\": \"#EF9A9A\", \"down\": \"#90CAF9\", \"stable\": \"#C8E6C9\"}\nrow_modules = ([\"up\"] * 14) + ([\"down\"] * 14) + ([\"stable\"] * 12)\nrow_colors  = [module_pal[m] for m in row_modules]\n\ng = sns.clustermap(\n    log_expr,\n    cmap=\"RdYlBu_r\",\n    center=log_expr.values.mean(),\n    standard_scale=0,           # z-score per gene (row)\n    method=\"ward\",\n    metric=\"euclidean\",\n    col_colors=col_colors,\n    row_colors=row_colors,\n    figsize=(14, 12),\n    linewidths=0,\n    cbar_pos=(0.02, 0.85, 0.03, 0.12),\n    cbar_kws={\"label\": \"Row z-score\"},\n    dendrogram_ratio=(0.12, 0.08),\n)\ng.ax_heatmap.set_xlabel(\"Sample\", fontsize=10)\ng.ax_heatmap.set_ylabel(\"Gene\",   fontsize=10)\ng.ax_heatmap.set_title(\"Gene Expression Clustermap\", fontsize=12, pad=80)\n\n# Manual legend for column\u002Frow annotations\nlegend_handles = [\n    mpatches.Patch(color=\"#C62828\", label=\"Tumor\"),\n    mpatches.Patch(color=\"#1565C0\", label=\"Normal\"),\n    mpatches.Patch(color=\"#EF9A9A\", label=\"Up in tumor\"),\n    mpatches.Patch(color=\"#90CAF9\", label=\"Down in tumor\"),\n    mpatches.Patch(color=\"#C8E6C9\", label=\"Stable\"),\n]\ng.ax_heatmap.legend(handles=legend_handles, bbox_to_anchor=(1.25, 1.05),\n                    loc=\"upper left\", frameon=False, fontsize=9)\n\nplt.savefig(\"clustermap_annotated.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved clustermap_annotated.png\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Legend placed outside plot, clipped in saved file | Figure-level functions place the legend outside by default | Add `bbox_inches=\"tight\"` to `savefig()`: `g.savefig(\"out.png\", dpi=300, bbox_inches=\"tight\")` |\n| `TypeError: FacetGrid.savefig()` or blank figure saved | Called `plt.savefig()` on a figure-level grid that owns its own figure | Use `g.savefig(...)` instead of `plt.savefig(...)` |\n| Overlapping x-axis category labels | Long label strings overlap at default rotation | Add `plt.xticks(rotation=45, ha=\"right\")` and `plt.tight_layout()` after the plot call |\n| `ValueError: Could not interpret value ... for parameter 'hue'` | Data is in wide-form; hue mapping requires long-form | Convert with `df.melt(id_vars=[...], var_name=\"sample\", value_name=\"expr\")` |\n| KDE bandwidth too smooth (loses bimodality) | Default `bw_adjust=1.0` over-smooths small datasets | Lower to `bw_adjust=0.5`; confirm peaks with `histplot` |\n| `clustermap` ignores `figsize` | Figure-level functions do not accept `figsize` as a kwarg in older seaborn | Pass `figsize` as a direct argument: `sns.clustermap(..., figsize=(12, 10))` |\n| Violin plot is a thin line (no shape) | Too few observations for KDE estimation | Switch to `kind=\"box\"` or `kind=\"strip\"`; or use `cut=0` to restrict KDE to data range |\n| Colors not distinguishable for many groups | Default palette repeats with >6 categories | Use `sns.color_palette(\"husl\", n_colors=N)` or `\"tab20\"` for up to 20 distinct colors |\n| Figure-level function ignores `ax=` parameter | Axes-level distinction: figure-level functions create their own figure | Use the corresponding axes-level function (`scatterplot`, `histplot`, etc.) with `ax=` |\n\n## Related Skills\n\n- **matplotlib-scientific-plotting** — low-level figure building, custom annotations, non-statistical plot types, and multi-panel layouts that mix seaborn with raw matplotlib\n- **plotly-interactive-plots** — interactive charts with hover, zoom, and HTML\u002FDash export\n- **pydeseq2-differential-expression** — produces the log2FC and p-values that feed into volcano-style scatter plots\n- **scikit-image-processing** — generates cell morphology measurements visualized with seaborn categorical\u002Fdistribution plots\n- **scientific-visualization** — decision guide for selecting the right chart type and color scheme before coding\n\n## References\n\n- [Seaborn official documentation](https:\u002F\u002Fseaborn.pydata.org\u002F) — API reference, tutorial, and gallery\n- [Seaborn example gallery](https:\u002F\u002Fseaborn.pydata.org\u002Fexamples\u002Findex.html) — visual index of all plot types\n- [Seaborn GitHub](https:\u002F\u002Fgithub.com\u002Fmwaskom\u002Fseaborn) — source code and issue tracker\n- Waskom ML (2021). \"seaborn: statistical data visualization.\" *Journal of Open Source Software*, 6(60), 3021. [https:\u002F\u002Fdoi.org\u002F10.21105\u002Fjoss.03021](https:\u002F\u002Fdoi.org\u002F10.21105\u002Fjoss.03021)\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fseaborn-statistical-plots",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill seaborn-statistical-plots",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill seaborn-statistical-plots",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill seaborn-statistical-plots","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fseaborn-statistical-plots\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]