Claude Code for Seaborn: Statistical Data Visualization — Claude Skills 360 Blog
Blog / AI / Claude Code for Seaborn: Statistical Data Visualization
AI

Claude Code for Seaborn: Statistical Data Visualization

Published: November 15, 2027
Read time: 5 min read
By: Claude Skills 360

Seaborn builds statistical visualizations on top of Matplotlib. pip install seaborn. import seaborn as sns. Theme: sns.set_theme(style="whitegrid", palette="muted", font_scale=1.2). Scatter: sns.scatterplot(data=df, x="col_a", y="col_b", hue="category", size="value"). Relplot: sns.relplot(data=df, x, y, col="facet", kind="scatter") — figure-level. Line: sns.lineplot(data=df, x, y, hue, estimator="mean", errorbar="ci"). Distribution: sns.histplot(df, x="value", kde=True, bins=50, hue="group", stat="density"). KDE: sns.kdeplot(df, x, y, fill=True, thresh=0.1). Displot: sns.displot(df, x, col="group", kind="kde") — faceted. Box: sns.boxplot(data=df, x="category", y="value", hue="group"). Violin: sns.violinplot(data=df, x, y, split=True, inner="quartile"). Strip: sns.stripplot(data=df, x, y, jitter=True, dodge=True). Heatmap: sns.heatmap(corr_matrix, annot=True, fmt=".2f", cmap="RdBu_r", vmin=-1, vmax=1, linewidths=0.5). Clustermap: sns.clustermap(df, method="ward", cmap="viridis", z_score=1). Pairplot: sns.pairplot(df, hue="class", diag_kind="kde", plot_kws={"alpha": 0.6}). Jointplot: sns.jointplot(data=df, x, y, kind="reg", marginal_kws={"bins":20}). Regression: sns.regplot(data=df, x, y, lowess=True). Lmplot: sns.lmplot(data=df, x, y, col="group", hue="sex"). FacetGrid: g = sns.FacetGrid(df, col="group", row="year"), g.map_dataframe(sns.scatterplot, x, y). Catplot: sns.catplot(data=df, x, y, col, kind="box", height=4). Objects API: so.Plot(df, x="x", y="y").add(so.Dot()).add(so.Line()).facet(col="group"). Save: plt.savefig("plot.png", dpi=150, bbox_inches="tight"). Claude Code generates Seaborn EDA dashboards, correlation heatmaps, faceted distribution plots, and regression visualization scripts.

CLAUDE.md for Seaborn

## Seaborn Stack
- Version: seaborn >= 0.13
- Theme: sns.set_theme(style, palette, font_scale) — call once at startup
- Axes-level: sns.scatterplot/lineplot/histplot/boxplot/heatmap(ax=ax)
- Figure-level: sns.relplot/displot/catplot/lmplot — return FacetGrid
- Pairwise: sns.pairplot(df, hue) | clustermap(matrix)
- Objects: from seaborn import objects as so — grammar-of-graphics API
- Save: plt.savefig(path, dpi=150, bbox_inches="tight") after any plot

Seaborn Statistical Visualization Pipeline

# viz/seaborn_pipeline.py — statistical data visualization with Seaborn
from __future__ import annotations
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path

# Global theme — call once
sns.set_theme(style="whitegrid", palette="muted", font_scale=1.1)
FIGSIZE_DEFAULT = (10, 6)


# ── 0. Helpers ────────────────────────────────────────────────────────────────

def _save(fig_or_ax, path: str, dpi: int = 150) -> str:
    """Save a figure to disk, creating parent dirs if needed."""
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    if isinstance(fig_or_ax, sns.FacetGrid):
        fig_or_ax.savefig(path, dpi=dpi, bbox_inches="tight")
    else:
        plt.savefig(path, dpi=dpi, bbox_inches="tight")
    plt.close("all")
    print(f"Saved: {path}")
    return path


# ── 1. Distribution plots ─────────────────────────────────────────────────────

def distribution_overview(
    df:         pd.DataFrame,
    col:        str,
    hue:        str = None,
    output:     str = "dist_overview.png",
    bins:       int = 40,
) -> str:
    """
    3-panel distribution overview: histogram+KDE, boxplot, ECDF.
    """
    fig, axes = plt.subplots(1, 3, figsize=(15, 4))

    # Histogram + KDE
    sns.histplot(data=df, x=col, hue=hue, kde=True, bins=bins, stat="density",
                 alpha=0.6, ax=axes[0])
    axes[0].set_title(f"Distribution of {col}")

    # Box plot
    if hue:
        sns.boxplot(data=df, x=hue, y=col, ax=axes[1])
    else:
        sns.boxplot(data=df, y=col, ax=axes[1])
    axes[1].set_title("Box plot")

    # ECDF
    sns.ecdfplot(data=df, x=col, hue=hue, ax=axes[2])
    axes[2].set_title("ECDF")

    fig.suptitle(f"{col} — Distribution Overview", y=1.02)
    plt.tight_layout()
    return _save(fig, output)


def kde_by_group(
    df:       pd.DataFrame,
    x:        str,
    group:    str,
    fill:     bool = True,
    output:   str = "kde_groups.png",
) -> str:
    """Overlapping KDE curves by group — useful for comparing distributions."""
    fig, ax = plt.subplots(figsize=FIGSIZE_DEFAULT)
    sns.kdeplot(data=df, x=x, hue=group, fill=fill, alpha=0.3,
                common_norm=False, ax=ax)
    ax.set_title(f"{x} density by {group}")
    plt.tight_layout()
    return _save(fig, output)


def faceted_distributions(
    df:       pd.DataFrame,
    x:        str,
    col:      str,
    row:      str = None,
    kind:     str = "hist",   # "hist" | "kde" | "ecdf"
    output:   str = "facet_dist.png",
) -> str:
    """Faceted distribution across a categorical variable."""
    g = sns.displot(data=df, x=x, col=col, row=row, kind=kind,
                    facet_kws={"sharey": False}, height=3, aspect=1.2)
    g.set_titles("{col_name}")
    plt.tight_layout()
    return _save(g, output)


# ── 2. Relationship plots ─────────────────────────────────────────────────────

def scatter_with_trend(
    df:         pd.DataFrame,
    x:          str,
    y:          str,
    hue:        str = None,
    lowess:     bool = False,
    output:     str = "scatter_trend.png",
) -> str:
    """Scatter plot with regression (or LOWESS) line."""
    fig, ax = plt.subplots(figsize=FIGSIZE_DEFAULT)
    sns.regplot(data=df, x=x, y=y, lowess=lowess,
                scatter_kws={"alpha": 0.4}, ax=ax)
    if hue:
        sns.scatterplot(data=df, x=x, y=y, hue=hue, alpha=0.6, ax=ax)
    ax.set_title(f"{y} vs {x}" + (" (LOWESS)" if lowess else " (OLS)"))
    plt.tight_layout()
    return _save(fig, output)


def pairplot(
    df:         pd.DataFrame,
    cols:       list[str] = None,
    hue:        str = None,
    diag_kind:  str = "kde",
    output:     str = "pairplot.png",
) -> str:
    """Pairplot for selected numeric columns."""
    data = df[cols] if cols else df.select_dtypes(include=np.number)
    if hue and hue in df.columns:
        data = pd.concat([data, df[[hue]]], axis=1)
    g = sns.pairplot(data, hue=hue, diag_kind=diag_kind,
                     plot_kws={"alpha": 0.5}, corner=True)
    g.figure.suptitle("Pairplot", y=1.01)
    return _save(g, output)


def line_with_ci(
    df:         pd.DataFrame,
    x:          str,
    y:          str,
    hue:        str = None,
    errorbar:   str = "ci",   # "ci" | "sd" | "se" | None
    output:     str = "lineplot.png",
) -> str:
    """Line plot with confidence interval band."""
    fig, ax = plt.subplots(figsize=FIGSIZE_DEFAULT)
    sns.lineplot(data=df, x=x, y=y, hue=hue, errorbar=errorbar,
                 markers=True, ax=ax)
    ax.set_title(f"{y} over {x}" + (f" by {hue}" if hue else ""))
    if "date" in x.lower() or "time" in x.lower():
        ax.tick_params(axis="x", rotation=45)
    plt.tight_layout()
    return _save(fig, output)


# ── 3. Categorical plots ──────────────────────────────────────────────────────

def categorical_comparison(
    df:      pd.DataFrame,
    x:       str,
    y:       str,
    hue:     str = None,
    kind:    str = "violin",  # "violin" | "box" | "bar" | "strip" | "point"
    output:  str = "cat_plot.png",
) -> str:
    """Compare a numeric value across categorical groups."""
    g = sns.catplot(
        data=df, x=x, y=y, hue=hue, kind=kind,
        height=5, aspect=1.4,
        order=df[x].value_counts().index.tolist() if df[x].nunique() < 20 else None,
    )
    g.set_titles(f"{kind} plot")
    g.set_xticklabels(rotation=30, ha="right")
    return _save(g, output)


def count_plot(
    df:      pd.DataFrame,
    col:     str,
    hue:     str = None,
    top_n:   int = 20,
    output:  str = "countplot.png",
) -> str:
    """Bar chart of category frequencies (top N by count)."""
    order = df[col].value_counts().iloc[:top_n].index.tolist()
    fig, ax = plt.subplots(figsize=(10, max(4, top_n * 0.35)))
    sns.countplot(data=df, y=col, hue=hue, order=order, ax=ax)
    ax.set_title(f"Count of {col}")
    plt.tight_layout()
    return _save(fig, output)


# ── 4. Heatmaps ───────────────────────────────────────────────────────────────

def correlation_heatmap(
    df:           pd.DataFrame,
    cols:         list[str] = None,
    method:       str = "pearson",
    annot:        bool = True,
    cmap:         str = "RdBu_r",
    output:       str = "correlation.png",
) -> str:
    """
    Annotated correlation heatmap.
    Masks upper triangle for cleaner reading.
    """
    data = df[cols] if cols else df.select_dtypes(include=np.number)
    corr = data.corr(method=method)

    # Mask upper triangle
    mask = np.triu(np.ones_like(corr), k=1)

    fig, ax = plt.subplots(figsize=(max(6, len(corr) * 0.6),
                                    max(5, len(corr) * 0.5)))
    sns.heatmap(
        corr, mask=mask, annot=annot, fmt=".2f",
        cmap=cmap, vmin=-1, vmax=1,
        linewidths=0.4, ax=ax,
    )
    ax.set_title(f"{method.capitalize()} Correlation Matrix")
    plt.tight_layout()
    return _save(fig, output)


def pivot_heatmap(
    df:       pd.DataFrame,
    index:    str,
    columns:  str,
    values:   str,
    aggfunc:  str = "mean",
    fmt:      str = ".1f",
    output:   str = "pivot_heatmap.png",
) -> str:
    """Heatmap of a pivot table — e.g. region × product sales."""
    pivot = df.pivot_table(index=index, columns=columns, values=values, aggfunc=aggfunc)
    fig_h = max(4, len(pivot) * 0.4 + 1)
    fig_w = max(6, len(pivot.columns) * 0.6 + 1)
    fig, ax = plt.subplots(figsize=(fig_w, fig_h))
    sns.heatmap(pivot, annot=True, fmt=fmt, cmap="YlOrRd", linewidths=0.4, ax=ax)
    ax.set_title(f"{values} ({aggfunc}) by {index} × {columns}")
    plt.tight_layout()
    return _save(fig, output)


def clustermap(
    df:       pd.DataFrame,
    cols:     list[str] = None,
    method:   str = "ward",
    z_score:  int = 1,         # 0=row, 1=col, None=off
    output:   str = "clustermap.png",
) -> str:
    """Hierarchical clustering heatmap (rows and columns)."""
    data = df[cols] if cols else df.select_dtypes(include=np.number)
    g = sns.clustermap(
        data, method=method, metric="euclidean",
        z_score=z_score, cmap="vlag",
        figsize=(max(6, data.shape[1] * 0.5 + 2),
                 max(6, data.shape[0] * 0.15 + 2)),
    )
    g.ax_heatmap.set_title("Hierarchical Clustermap")
    return _save(g, output)


# ── 5. FacetGrid ──────────────────────────────────────────────────────────────

def faceted_scatter(
    df:      pd.DataFrame,
    x:       str,
    y:       str,
    col:     str,
    hue:     str = None,
    row:     str = None,
    output:  str = "facet_scatter.png",
) -> str:
    """Scatter plots faceted by a categorical variable."""
    g = sns.FacetGrid(df, col=col, row=row, hue=hue,
                      height=3.5, aspect=1.2, margin_titles=True)
    g.map_dataframe(sns.scatterplot, x=x, y=y, alpha=0.5)
    g.add_legend()
    g.set_titles(col_template="{col_name}")
    return _save(g, output)


# ── 6. Seaborn Objects (v0.13+) ───────────────────────────────────────────────

def objects_scatter_line(
    df:      pd.DataFrame,
    x:       str,
    y:       str,
    color:   str = None,
    output:  str = "so_plot.png",
) -> str:
    """
    Grammar-of-graphics style layered plot using seaborn.objects.
    Dot layer + smooth trend line.
    """
    from seaborn import objects as so

    p = (
        so.Plot(df, x=x, y=y, color=color)
        .add(so.Dot(alpha=0.4))
        .add(so.Line(), so.PolyFit(order=2))
        .theme({"axes.spines.top": False, "axes.spines.right": False})
    )
    fig = p.plot()
    return _save(fig, output)


# ── Demo ──────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import tempfile, os
    print("Seaborn Statistical Visualization Demo")
    print("=" * 50)

    # Sample data
    np.random.seed(42)
    n = 500
    df = pd.DataFrame({
        "age":      np.random.randint(18, 75, n),
        "income":   np.random.lognormal(10.5, 0.7, n),
        "score":    np.random.normal(65, 15, n).clip(0, 100),
        "region":   np.random.choice(["North", "South", "East", "West"], n),
        "product":  np.random.choice(["A", "B", "C"], n),
        "churn":    np.random.choice(["Yes", "No"], n, p=[0.3, 0.7]),
    })

    with tempfile.TemporaryDirectory() as tmpdir:
        # Distribution overview
        path = distribution_overview(df, "income", hue="churn",
                                     output=f"{tmpdir}/dist.png")
        print(f"Distribution plot: {path}")

        # Correlation heatmap
        path = correlation_heatmap(df, cols=["age", "income", "score"],
                                   output=f"{tmpdir}/corr.png")
        print(f"Correlation heatmap: {path}")

        # Categorical violin plot
        path = categorical_comparison(df, x="region", y="income", hue="churn",
                                      kind="violin", output=f"{tmpdir}/violin.png")
        print(f"Violin plot: {path}")

        # Pivot heatmap
        path = pivot_heatmap(df, index="region", columns="product", values="score",
                              output=f"{tmpdir}/pivot.png")
        print(f"Pivot heatmap: {path}")

        # Line with CI (time series)
        ts_df = pd.DataFrame({
            "month":  np.tile(range(24), 4),
            "sales":  np.random.normal(1000, 150, 96),
            "region": np.repeat(["N","S","E","W"], 24),
        })
        path = line_with_ci(ts_df, x="month", y="sales", hue="region",
                            output=f"{tmpdir}/lineplot.png")
        print(f"Line + CI plot: {path}")

    print("\nAll plots saved successfully")

For the Matplotlib alternative when full control over every rendering detail is required — Matplotlib provides pixel-level customization of every element while Seaborn’s catplot, displot, and relplot produce publication-quality statistical graphics with correct default aesthetics in one function call, and the hue semantic automatically assigns distinct colors and a legend without manual plt.scatter calls for each group. For the Plotly alternative when interactive hover and zoom matter — Plotly produces interactive HTML charts while Seaborn’s clustermap with built-in hierarchical ordering, pairplot with per-diagonal KDE, and regplot with confidence bands plus residuals in a single call combine statistical computation with rendering that would require 50+ lines in Plotly’s graph_objects API, making Seaborn the faster path for EDA and statistical reporting. The Claude Skills 360 bundle includes Seaborn skill sets covering histogram and KDE distribution plots, correlation heatmaps with triangle masking, violin and box categorical comparisons, faceted scatter and distribution grids, pairplot and clustermap, lineplot with confidence intervals, pivot heatmaps, and the Objects grammar-of-graphics API. Start with the free tier to try statistical visualization code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free