Chris Parmer — home

Chromatogram

Analytical Chemistry

Example from the compendium of canonical charts

Analytical Chemistry — Chromatogram

Python Code

"""Analytical Chemistry — Chromatogram."""
from pathlib import Path

# ── Palette + theme (matching the Plotly Studio gallery these charts ship in) ──
VIOLET, TEAL, GREEN, PINK, ORANGE = "#845EEE", "#52B3D0", "#55B685", "#DA5597", "#E9A23B"
PRIMARY, SECONDARY = VIOLET, TEAL
COLORWAY = [VIOLET, TEAL, GREEN, PINK, ORANGE]
BG, TEXT, GRID, MUTED = "#ffffff", "#1c2024", "#d9d9e0", "#60646c"
FONT = "Inter, -apple-system, BlinkMacSystemFont, sans-serif"
COLORSCALE = [[0, "rgba(132, 94, 238, 0.05)"], [1, "rgba(132, 94, 238, 0.9)"]]


def apply_theme(fig):
    """Light gallery theme: white background, Inter font, soft gridlines."""
    fig.update_layout(
        paper_bgcolor=BG, plot_bgcolor=BG, colorway=COLORWAY,
        font=dict(family=FONT, color=TEXT, size=12),
        legend=dict(font=dict(color=TEXT)),
        hoverlabel=dict(bgcolor="#f0f0f3", font=dict(color=TEXT, family=FONT), bordercolor=GRID),
    )
    fig.update_xaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
    fig.update_yaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)


def fetch_csv(url, **kwargs):
    import io
    import pandas as pd
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return pd.read_csv(io.StringIO(r.text), **kwargs)


def fetch_json(url):
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return r.json()

import numpy as np
import plotly.graph_objects as go

URL = "https://raw.githubusercontent.com/cremerlab/hplc-py/main/tests/test_data/test_assessment_chrom.csv"


def generate():
    print("fetching chromatogram data …")
    try:
        df = fetch_csv(URL)
        print(f"  cols: {list(df.columns)}, shape: {df.shape}")
        # Try to identify x/y columns
        if "x" in df.columns and "y" in df.columns:
            time = df["x"].values
            signal = df["y"].values
        elif "time" in df.columns.str.lower().tolist():
            tc = [c for c in df.columns if c.lower() == "time"][0]
            sc = [c for c in df.columns if c.lower() not in ("time",)][0]
            time = df[tc].values
            signal = df[sc].values
        else:
            time = df.iloc[:, 0].values
            signal = df.iloc[:, 1].values
        used_synthetic = False
    except Exception as e:
        print(f"  fetch failed ({e}); using synthetic chromatogram")
        used_synthetic = True
        rng = np.random.default_rng(42)
        time = np.linspace(0, 35.7, 3570)
        # Gaussian peaks at several retention times
        def gauss(t, mu, sigma, amp):
            return amp * np.exp(-0.5 * ((t - mu) / sigma) ** 2)
        signal = (
            gauss(time, 5.2, 0.3, 800)
            + gauss(time, 9.8, 0.5, 1500)
            + gauss(time, 14.5, 0.4, 600)
            + gauss(time, 20.1, 0.6, 2200)
            + gauss(time, 28.3, 0.8, 900)
            + rng.normal(0, 15, len(time))
        )

    # Detect peaks: local maxima above threshold
    from scipy.signal import find_peaks
    threshold = np.mean(signal) + 2 * np.std(signal)
    peak_indices, props = find_peaks(signal, height=threshold, distance=50)
    peak_indices = peak_indices[np.argsort(signal[peak_indices])[::-1]]  # sort by height

    print(f"  detected {len(peak_indices)} major peaks above threshold {threshold:.1f}")

    peak_x = time[peak_indices]
    peak_y = signal[peak_indices]
    peak_labels = [f"Peak {i+1}" for i in range(len(peak_indices))]

    fig = go.Figure()

    # Main trace
    fig.add_trace(go.Scatter(
        x=time,
        y=signal,
        mode="lines",
        name="Signal",
        line=dict(color=VIOLET, width=1.5),
        hovertemplate="t=%{x:.2f} min<br>Signal=%{y:.1f} mAU<extra></extra>",
    ))

    # Peak markers
    fig.add_trace(go.Scatter(
        x=peak_x,
        y=peak_y,
        mode="markers+text",
        name="Peaks",
        marker=dict(color=TEAL, size=10, symbol="circle-open", line=dict(width=2)),
        text=peak_labels,
        textposition="top center",
        textfont=dict(size=11),
        hovertemplate="%{text}<br>t=%{x:.2f} min<br>Signal=%{y:.1f} mAU<extra></extra>",
    ))

    fig.update_layout(
        xaxis=dict(title="Retention Time (min)", range=[time.min(), time.max()]),
        yaxis=dict(title="Signal (mAU)"),
        legend=dict(orientation="h", y=1.05, x=0),
        margin=dict(t=50, b=60, l=70, r=60),
    )
    apply_theme(fig)
    return fig


fig = generate()
fig.show()

Made with Plotly