Claude Code for Plotly: Interactive Data Visualization — Claude Skills 360 Blog
Blog / AI / Claude Code for Plotly: Interactive Data Visualization
AI

Claude Code for Plotly: Interactive Data Visualization

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

Plotly creates interactive web-ready charts with hover, zoom, and pan. pip install plotly. import plotly.express as px, import plotly.graph_objects as go. Quick scatter: fig = px.scatter(df, x="col_a", y="col_b", color="category", size="value", hover_data=["label"]). Line chart: px.line(df, x="date", y="value", color="series"). Bar: px.bar(df, x="name", y="count", text_auto=True). Histogram: px.histogram(df, x="value", nbins=50, color="group"). Box: px.box(df, x="category", y="value", points="all"). Heatmap: px.imshow(matrix, color_continuous_scale="RdBu_r", zmin=-1, zmax=1). Map: px.choropleth(df, locations="iso_code", color="rate", scope="world"). Scatter 3D: px.scatter_3d(df, x, y, z, color="group"). Facet: px.scatter(df, facet_col="location", facet_row="year"). Animation: px.scatter(df, x, y, animation_frame="year", size="pop"). Template: fig.update_layout(template="plotly_dark"). Subplots: from plotly.subplots import make_subplots, fig = make_subplots(rows=2, cols=2), fig.add_trace(go.Scatter(...), row=1, col=1). Export: fig.write_html("chart.html"), fig.write_image("chart.png") — needs kaleido. Show: fig.show() in browser or notebook. Graph objects: go.Figure(data=[go.Candlestick(x=dates, open=o, high=h, low=l, close=c)]). Shared axes: make_subplots(shared_xaxes=True, shared_yaxes=True). Custom tooltip: go.Scatter(hovertemplate="%{x}: %{y:.2f}<extra></extra>"). Claude Code generates Plotly dashboards, animated time-series charts, geographic maps, financial candlestick charts, and correlation heatmaps.

CLAUDE.md for Plotly

## Plotly Stack
- Version: plotly >= 5.20
- Express: px.scatter/line/bar/histogram/box/heatmap/choropleth(df, x, y, color, ...)
- Objects: go.Figure(data=[go.Scatter/Bar/Heatmap/Candlestick/Surface(...)])
- Layout: fig.update_layout(title, xaxis_title, template, height, width)
- Subplots: make_subplots(rows, cols) → fig.add_trace(trace, row, col)
- Export: fig.write_html(path) | fig.write_image(path) [needs kaleido]
- Show: fig.show() | fig in Jupyter renders inline
- Color: color_continuous_scale | color_discrete_map | colorway

Plotly Visualization Pipeline

# viz/plotly_pipeline.py — interactive data visualization with Plotly
from __future__ import annotations
import numpy as np
import pandas as pd
from pathlib import Path

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.io as pio

# Default theme
pio.templates.default = "plotly_white"


# ── 1. Express charts ─────────────────────────────────────────────────────────

def scatter_chart(
    df:          pd.DataFrame,
    x:           str,
    y:           str,
    color:       str = None,
    size:        str = None,
    hover_data:  list[str] = None,
    trendline:   str = None,   # "ols" | "lowess"
    title:       str = "",
    labels:      dict = None,
) -> go.Figure:
    """Interactive scatter plot with optional regression trendline."""
    fig = px.scatter(
        df, x=x, y=y, color=color, size=size,
        hover_data=hover_data, trendline=trendline,
        title=title, labels=labels or {},
        template="plotly_white",
    )
    return fig


def line_chart(
    df:          pd.DataFrame,
    x:           str,
    y:           str | list[str] = None,
    color:       str = None,
    markers:     bool = False,
    title:       str = "",
    y_title:     str = None,
    x_title:     str = None,
) -> go.Figure:
    """Interactive line chart — supports multiple y columns."""
    if isinstance(y, list):
        # Melt for multiple lines
        df_melt = df.melt(id_vars=[x], value_vars=y, var_name="series", value_name="value")
        fig = px.line(df_melt, x=x, y="value", color="series", markers=markers, title=title)
    else:
        fig = px.line(df, x=x, y=y, color=color, markers=markers, title=title)

    if y_title:
        fig.update_yaxes(title_text=y_title)
    if x_title:
        fig.update_xaxes(title_text=x_title)
    return fig


def bar_chart(
    df:        pd.DataFrame,
    x:         str,
    y:         str,
    color:     str = None,
    barmode:   str = "group",  # "group" | "stack" | "relative"
    horizontal: bool = False,
    text_auto: bool = True,
    title:     str = "",
) -> go.Figure:
    """
    Bar chart with optional grouping/stacking.
    horizontal=True flips axes for long category names.
    """
    kwargs = dict(x=x, y=y, color=color, barmode=barmode,
                  text_auto=text_auto, title=title)
    if horizontal:
        kwargs["x"], kwargs["y"] = kwargs["y"], kwargs["x"]
        fig = px.bar(df, orientation="h", **kwargs)
    else:
        fig = px.bar(df, **kwargs)
    return fig


def histogram_chart(
    df:       pd.DataFrame,
    x:        str,
    color:    str = None,
    nbins:    int = 50,
    barmode:  str = "overlay",
    opacity:  float = 0.7,
    add_kde:  bool  = True,
    title:    str = "",
) -> go.Figure:
    """Histogram with optional KDE overlay."""
    fig = px.histogram(
        df, x=x, color=color, nbins=nbins,
        barmode=barmode, opacity=opacity,
        marginal="rug" if add_kde else None,
        title=title,
    )
    return fig


# ── 2. Correlation and heatmaps ───────────────────────────────────────────────

def correlation_heatmap(
    df:          pd.DataFrame,
    columns:     list[str] = None,
    method:      str = "pearson",
    colorscale:  str = "RdBu_r",
    title:       str = "Correlation Matrix",
) -> go.Figure:
    """Interactive correlation heatmap with hover values."""
    cols   = columns or list(df.select_dtypes(include=np.number).columns)
    corr   = df[cols].corr(method=method)

    fig = px.imshow(
        corr,
        color_continuous_scale=colorscale,
        zmin=-1, zmax=1,
        text_auto=".2f",
        title=title,
        aspect="auto",
    )
    fig.update_coloraxes(colorbar_title="r")
    return fig


def matrix_heatmap(
    matrix:      np.ndarray,
    x_labels:    list[str] = None,
    y_labels:    list[str] = None,
    colorscale:  str = "Viridis",
    title:       str = "",
    text_format: str = ".2f",
) -> go.Figure:
    """General matrix heatmap."""
    fig = px.imshow(
        matrix,
        x=x_labels, y=y_labels,
        color_continuous_scale=colorscale,
        text_auto=text_format if text_format else False,
        title=title,
    )
    return fig


# ── 3. Time series dashboard ──────────────────────────────────────────────────

def time_series_dashboard(
    df:        pd.DataFrame,
    date_col:  str,
    value_col: str,
    group_col: str = None,
    rolling:   int = None,
    title:     str = "Time Series Dashboard",
) -> go.Figure:
    """
    Multi-panel time series dashboard:
    - Row 1: Main time series with optional rolling mean
    - Row 2: Daily/period changes
    """
    fig = make_subplots(
        rows=2, cols=1,
        shared_xaxes=True,
        subplot_titles=["Value Over Time", "Period Change"],
        row_heights=[0.7, 0.3],
        vertical_spacing=0.05,
    )

    if group_col:
        groups = df[group_col].unique()
        for group in groups:
            gdf = df[df[group_col] == group].sort_values(date_col)
            fig.add_trace(go.Scatter(
                x=gdf[date_col], y=gdf[value_col],
                mode="lines", name=str(group),
            ), row=1, col=1)

            if rolling and len(gdf) >= rolling:
                rm = gdf[value_col].rolling(rolling).mean()
                fig.add_trace(go.Scatter(
                    x=gdf[date_col], y=rm,
                    mode="lines", name=f"{group} MA{rolling}",
                    line=dict(dash="dash"),
                    showlegend=False,
                ), row=1, col=1)
    else:
        df_sorted = df.sort_values(date_col)
        fig.add_trace(go.Scatter(
            x=df_sorted[date_col], y=df_sorted[value_col],
            mode="lines+markers", name="Value",
        ), row=1, col=1)

        pct_change = df_sorted[value_col].pct_change() * 100
        colors     = ["green" if v >= 0 else "red" for v in pct_change.fillna(0)]
        fig.add_trace(go.Bar(
            x=df_sorted[date_col], y=pct_change,
            marker_color=colors, name="% Change",
        ), row=2, col=1)

    fig.update_layout(title=title, hovermode="x unified", height=600)
    return fig


def candlestick_chart(
    df:          pd.DataFrame,
    date_col:    str = "date",
    open_col:    str = "open",
    high_col:    str = "high",
    low_col:     str = "low",
    close_col:   str = "close",
    volume_col:  str = "volume",
    title:       str = "Price Chart",
) -> go.Figure:
    """Financial candlestick chart with optional volume bars."""
    has_volume = volume_col in df.columns

    if has_volume:
        fig = make_subplots(
            rows=2, cols=1, shared_xaxes=True,
            row_heights=[0.8, 0.2], vertical_spacing=0.02,
        )
    else:
        fig = make_subplots(rows=1, cols=1)

    fig.add_trace(go.Candlestick(
        x=df[date_col], open=df[open_col],
        high=df[high_col], low=df[low_col],
        close=df[close_col], name="OHLC",
    ), row=1, col=1)

    if has_volume:
        colors = ["green" if c >= o else "red"
                  for c, o in zip(df[close_col], df[open_col])]
        fig.add_trace(go.Bar(
            x=df[date_col], y=df[volume_col],
            marker_color=colors, name="Volume",
        ), row=2, col=1)

    fig.update_layout(
        title=title, xaxis_rangeslider_visible=False,
        height=500 + (150 if has_volume else 0),
    )
    return fig


# ── 4. Multi-panel dashboard ──────────────────────────────────────────────────

def multi_panel_dashboard(
    charts:   list[dict],   # [{"fig": go.Figure, "title": str}, ...]
    n_cols:   int = 2,
    title:    str = "Dashboard",
    height:   int = 800,
) -> go.Figure:
    """
    Combine multiple Plotly figures into a grid layout.
    Each chart dict: {"fig": fig, "title": str}.
    """
    n_rows  = (len(charts) + n_cols - 1) // n_cols
    subplot_titles = [c.get("title", "") for c in charts]

    fig = make_subplots(
        rows=n_rows, cols=n_cols,
        subplot_titles=subplot_titles,
    )

    for i, chart_info in enumerate(charts):
        row = i // n_cols + 1
        col = i %  n_cols + 1
        for trace in chart_info["fig"].data:
            fig.add_trace(trace, row=row, col=col)

    fig.update_layout(title_text=title, height=height, showlegend=False)
    return fig


# ── 5. 3D and animated charts ─────────────────────────────────────────────────

def scatter_3d(
    df:         pd.DataFrame,
    x:          str,
    y:          str,
    z:          str,
    color:      str = None,
    size:       str = None,
    title:      str = "3D Scatter",
) -> go.Figure:
    """Interactive 3D scatter plot."""
    return px.scatter_3d(df, x=x, y=y, z=z, color=color, size=size, title=title)


def animated_scatter(
    df:              pd.DataFrame,
    x:               str,
    y:               str,
    animation_frame: str,
    size:            str = None,
    color:           str = None,
    title:           str = "",
) -> go.Figure:
    """Animated scatter chart (Gapminder-style) with play button."""
    return px.scatter(
        df, x=x, y=y,
        animation_frame=animation_frame,
        animation_group=color,
        size=size, color=color,
        title=title,
        size_max=60,
    )


# ── 6. Export ─────────────────────────────────────────────────────────────────

def save_html(fig: go.Figure, path: str, include_plotlyjs: str = "cdn") -> str:
    """Save interactive HTML (cdn = small file; True = self-contained)."""
    fig.write_html(path, include_plotlyjs=include_plotlyjs)
    print(f"Saved HTML: {path}")
    return path


def save_image(fig: go.Figure, path: str, scale: float = 2.0) -> str:
    """
    Save static PNG/SVG/PDF (requires kaleido: pip install kaleido).
    scale=2 for high-resolution (192 DPI equivalent).
    """
    fig.write_image(path, scale=scale)
    print(f"Saved image: {path}")
    return path


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

if __name__ == "__main__":
    print("Plotly Visualization Demo")
    print("="*50)

    # Sample data
    dates  = pd.date_range("2023-01-01", periods=100, freq="D")
    values = np.cumsum(np.random.randn(100)) + 100
    df_ts  = pd.DataFrame({"date": dates, "value": values})
    df_ts["change"] = df_ts["value"].pct_change() * 100

    # Time series
    fig  = time_series_dashboard(df_ts, "date", "value", rolling=7)
    save_html(fig, "/tmp/timeseries.html")

    # Correlation heatmap
    df_num = pd.DataFrame(np.random.randn(200, 5), columns=list("ABCDE"))
    fig_corr = correlation_heatmap(df_num)
    save_html(fig_corr, "/tmp/correlation.html")

    # Scatter with trendline
    df_scatter = pd.DataFrame({
        "x": np.random.randn(200),
        "y": 2.5 * np.random.randn(200),
        "cat": np.random.choice(["A", "B", "C"], 200),
    })
    fig_sc = scatter_chart(df_scatter, "x", "y", color="cat", trendline="ols")
    save_html(fig_sc, "/tmp/scatter.html")

    print("\nAll charts saved to /tmp/")

For the matplotlib alternative when needing publication-quality static figures with full LaTeX rendering, custom subplot geometries, or 3D surface plots for journals — matplotlib produces print-ready PDFs while Plotly’s default interactive HTML output with built-in zoom, pan, hover tooltips, and linked subplots eliminates the need to write custom event handlers for exploratory data analysis, and the fig.write_html single-file portable charts work in any browser without server infrastructure. For the Bokeh alternative when building streaming real-time dashboards or embedding charts in web applications without a Python server — Bokeh uses JavaScript callbacks for client-side updates while Plotly’s Dash framework provides a full Python-based reactive web application layer for interactive dashboards, and Plotly Express’s one-liner API for complex visualizations (faceted, animated, 3D) is significantly more concise than Bokeh’s explicit glyph-builder API for common EDA charts. The Claude Skills 360 bundle includes Plotly skill sets covering scatter, line, bar, histogram, and box charts, correlation heatmaps, time series dashboards, candlestick financial charts, 3D scatter, animated charts, make_subplots grid layouts, and HTML and image export. Start with the free tier to try interactive 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