Chris Parmer — home

Chromatogram

Analytical Chemistry

Example from the compendium of canonical charts

Analytical Chemistry — Chromatogram

Python Code

"""Analytical Chemistry — Chromatogram."""


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),
    )
    return fig


if __name__ == "__main__":
    generate()

Made with Plotly