Skip to content

API Reference: ecg_sdk.visualization.plotter

ecg_sdk.visualization.plotter

Clinical ECG Plotting Module

Renders single-lead, multi-lead, and standard 12-lead electrocardiograms with authentic clinical millimeter paper grid formatting, precise voltage/time calibration, fiducial wave annotations, adaptive anti-collision layout, configurable sparse tick labeling, and physical 1:1 "paper" mode vs responsive "digital" display modes.

Standard Clinical Specifications (IEC 60601-2-25 / AHA / ACC / ESC): - Paper Speed: 25 mm/s (1 small square [1 mm] = 0.04 s; 1 large block [5 mm] = 0.20 s) - Voltage Sensitivity / Gain: 10 mm/mV (1 small square [1 mm] = 0.10 mV; 1 large block [5 mm] = 0.50 mV) - Calibration Pulse: Standard 1.0 mV square pulse with 0.20 s duration (5 mm x 10 mm) - Physical Print Sizes: * 12-Lead Diagnostic Page: US Letter (11" x 8.5") or ISO A4 (297 mm x 210 mm) * Ambulatory / Holter Thermal Strip: 50 mm (approx 2.0") height per channel

GRID_STYLES = {'clinical_pink': {'bg_color': '#fff5f5', 'minor_color': '#fed7d7', 'major_color': '#feb2b2', 'minor_alpha': 0.65, 'major_alpha': 0.95, 'minor_lw': 0.45, 'major_lw': 0.85, 'signal_color': '#0a0a0a', 'signal_lw': 1.25, 'text_color': '#1a202c', 'border_color': '#e53e3e'}, 'clinical_red': {'bg_color': '#fef2f2', 'minor_color': '#fecaca', 'major_color': '#f87171', 'minor_alpha': 0.65, 'major_alpha': 0.95, 'minor_lw': 0.45, 'major_lw': 0.85, 'signal_color': '#000000', 'signal_lw': 1.25, 'text_color': '#111827', 'border_color': '#b91c1c'}, 'clinical_gray': {'bg_color': '#ffffff', 'minor_color': '#e2e8f0', 'major_color': '#94a3b8', 'minor_alpha': 0.6, 'major_alpha': 0.9, 'minor_lw': 0.45, 'major_lw': 0.85, 'signal_color': '#0f172a', 'signal_lw': 1.25, 'text_color': '#0f172a', 'border_color': '#64748b'}, 'dark_telemetry': {'bg_color': '#0b1120', 'minor_color': '#1e293b', 'major_color': '#334155', 'minor_alpha': 0.5, 'major_alpha': 0.8, 'minor_lw': 0.45, 'major_lw': 0.85, 'signal_color': '#10b981', 'signal_lw': 1.35, 'text_color': '#f8fafc', 'border_color': '#475569'}} module-attribute

plot_clinical_ecg(signal, lead=0, start_time=0.0, duration=10.0, display_mode='paper', speed_mm_s=25.0, gain_mm_mv=10.0, grid_style='clinical_pink', voltage_range=None, ylim=None, plot_height=None, height_per_lead=None, figsize=None, r_peaks=None, waves=None, annotations=None, time_tick_step=None, voltage_tick_step=None, sparse_ticks=True, show_calibration_pulse=True, show_header=True, title=None, save_path=None)

Plot a single or multi-lead ECG strip on standard clinical ECG paper.

Parameters:

Name Type Description Default
signal ECGSignal

ECGSignal instance.

required
lead Optional[Union[str, int]]

Index or string name of lead to plot. If None, plots all leads stacked.

0
start_time float

Start time in seconds.

0.0
duration Optional[float]

Duration of window to plot in seconds (defaults to 10s or total duration).

10.0
display_mode str

'paper' (exact 1:1 physical millimeter scale matching thermal paper rolls) or 'digital' (expanded responsive layout optimized for monitors and slides).

'paper'
speed_mm_s float

Standard paper speed (default: 25.0 mm/s).

25.0
gain_mm_mv float

Standard voltage gain (default: 10.0 mm/mV).

10.0
grid_style str

Color palette: 'clinical_pink', 'clinical_red', 'clinical_gray', 'dark_telemetry'.

'clinical_pink'
voltage_range Optional[Tuple[float, float]]

Optional (min_mv, max_mv) tuple to fix vertical voltage scale.

None
ylim Optional[Tuple[float, float]]

Alias for voltage_range.

None
plot_height Optional[float]

Total figure height in inches (overrides display_mode defaults).

None
height_per_lead Optional[float]

Height in inches per stacked lead track.

None
figsize Optional[Tuple[float, float]]

Optional (width, height) in inches.

None
r_peaks Optional[ndarray]

1D array of sample indices for detected R-peaks within the window.

None
waves Optional[Dict[str, ndarray]]

Dictionary of fiducial wave sample indices, e.g. {'P': p_idx, 'QRS_onset': qon_idx, 'T': t_idx}.

None
annotations Optional[List[Dict[str, Any]]]

List of dicts specifying text annotations at given timestamps.

None
time_tick_step Optional[float]

Step interval in seconds for X-axis numeric labels (e.g. 1.0s).

None
voltage_tick_step Optional[float]

Step interval in mV for Y-axis numeric labels (e.g. 0.5mV or 1.0mV).

None
sparse_ticks bool

If True, renders uncluttered labels at clean intervals while keeping full grid.

True
show_calibration_pulse bool

Whether to prepend the standard 1 mV reference pulse.

True
show_header bool

Whether to render the clinical medical header banner on top.

True
title Optional[str]

Optional custom title for the strip.

None
save_path Optional[str]

Optional file path to export high-resolution image (PNG, PDF, SVG).

None

Returns:

Type Description
Tuple[Figure, Any]

(fig, ax) or (fig, axes) Matplotlib objects.

Source code in ecg_sdk/visualization/plotter.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def plot_clinical_ecg(
    signal: ECGSignal,
    lead: Optional[Union[str, int]] = 0,
    start_time: float = 0.0,
    duration: Optional[float] = 10.0,
    display_mode: str = "paper",
    speed_mm_s: float = 25.0,
    gain_mm_mv: float = 10.0,
    grid_style: str = "clinical_pink",
    voltage_range: Optional[Tuple[float, float]] = None,
    ylim: Optional[Tuple[float, float]] = None,
    plot_height: Optional[float] = None,
    height_per_lead: Optional[float] = None,
    figsize: Optional[Tuple[float, float]] = None,
    r_peaks: Optional[np.ndarray] = None,
    waves: Optional[Dict[str, np.ndarray]] = None,
    annotations: Optional[List[Dict[str, Any]]] = None,
    time_tick_step: Optional[float] = None,
    voltage_tick_step: Optional[float] = None,
    sparse_ticks: bool = True,
    show_calibration_pulse: bool = True,
    show_header: bool = True,
    title: Optional[str] = None,
    save_path: Optional[str] = None,
) -> Tuple[plt.Figure, Any]:
    """
    Plot a single or multi-lead ECG strip on standard clinical ECG paper.

    Args:
        signal: ECGSignal instance.
        lead: Index or string name of lead to plot. If None, plots all leads stacked.
        start_time: Start time in seconds.
        duration: Duration of window to plot in seconds (defaults to 10s or total duration).
        display_mode: 'paper' (exact 1:1 physical millimeter scale matching thermal paper rolls)
                      or 'digital' (expanded responsive layout optimized for monitors and slides).
        speed_mm_s: Standard paper speed (default: 25.0 mm/s).
        gain_mm_mv: Standard voltage gain (default: 10.0 mm/mV).
        grid_style: Color palette: 'clinical_pink', 'clinical_red', 'clinical_gray', 'dark_telemetry'.
        voltage_range: Optional (min_mv, max_mv) tuple to fix vertical voltage scale.
        ylim: Alias for voltage_range.
        plot_height: Total figure height in inches (overrides display_mode defaults).
        height_per_lead: Height in inches per stacked lead track.
        figsize: Optional (width, height) in inches.
        r_peaks: 1D array of sample indices for detected R-peaks within the window.
        waves: Dictionary of fiducial wave sample indices, e.g. {'P': p_idx, 'QRS_onset': qon_idx, 'T': t_idx}.
        annotations: List of dicts specifying text annotations at given timestamps.
        time_tick_step: Step interval in seconds for X-axis numeric labels (e.g. 1.0s).
        voltage_tick_step: Step interval in mV for Y-axis numeric labels (e.g. 0.5mV or 1.0mV).
        sparse_ticks: If True, renders uncluttered labels at clean intervals while keeping full grid.
        show_calibration_pulse: Whether to prepend the standard 1 mV reference pulse.
        show_header: Whether to render the clinical medical header banner on top.
        title: Optional custom title for the strip.
        save_path: Optional file path to export high-resolution image (PNG, PDF, SVG).

    Returns:
        (fig, ax) or (fig, axes) Matplotlib objects.
    """
    style = GRID_STYLES.get(grid_style, GRID_STYLES["clinical_pink"])

    # Slice recording to requested window
    end_time = min(signal.duration, start_time + duration) if duration else signal.duration
    sliced_sig = signal.slice(start_time=start_time, end_time=end_time)

    # Determine leads to plot
    if lead is None:
        selected_leads = list(range(sliced_sig.n_leads))
    elif isinstance(lead, (int, str)):
        if isinstance(lead, str):
            lead_idx = sliced_sig.lead_names.index(lead)
        else:
            lead_idx = lead
        selected_leads = [lead_idx]
    else:
        selected_leads = [0]

    n_plots = len(selected_leads)
    t_vector = sliced_sig.time_vector

    # Time boundaries
    cal_offset = 0.35 if show_calibration_pulse else 0.0
    t_min = -cal_offset if show_calibration_pulse else 0.0
    t_max = sliced_sig.duration
    total_time_span = t_max + cal_offset

    # Compute overall signal voltage limits across selected leads
    selected_data = [sliced_sig.get_lead(li) for li in selected_leads]
    overall_min = min(np.min(d) for d in selected_data)
    overall_max = max(np.max(d) for d in selected_data)

    # -------------------------------------------------------------------------
    # Voltage Limits Calculation (Prevents Clipping with Amplitude-Adaptive Headroom)
    # -------------------------------------------------------------------------
    v_limits = voltage_range or ylim
    if v_limits is not None:
        v_min, v_max = v_limits
    else:
        # Check if signal fits in standard clinical window [-1.5, 2.0]
        if overall_min >= -1.3 and overall_max <= 1.8:
            v_min = -1.5
            v_max = 2.0
        elif overall_min >= -1.8 and overall_max <= 2.3:
            v_min = -2.0
            v_max = 2.5
        else:
            # Dynamically expand in 0.5 mV steps to guarantee zero clipping
            v_min = np.floor((overall_min - 0.40) / 0.5) * 0.5
            v_max = np.ceil((overall_max + 0.60) / 0.5) * 0.5

    voltage_span = v_max - v_min

    # -------------------------------------------------------------------------
    # Physical Figure Sizing Engine (Paper 1:1 vs Digital)
    # -------------------------------------------------------------------------
    is_paper = str(display_mode).lower().strip() == "paper"

    if figsize is not None:
        fig_width, fig_height = figsize
    elif plot_height is not None:
        if is_paper:
            fig_width = (total_time_span * speed_mm_s) / MM_PER_INCH
        else:
            fig_width = max(12.0, total_time_span * 1.35)
        fig_height = float(plot_height)
    elif height_per_lead is not None:
        if is_paper:
            fig_width = (total_time_span * speed_mm_s) / MM_PER_INCH
        else:
            fig_width = max(12.0, total_time_span * 1.35)
        header_space = 0.6 if show_header else 0.2
        fig_height = float(height_per_lead * n_plots + header_space)
    else:
        if is_paper:
            # Exact 1:1 physical millimeter scale:
            # Width: 25 mm per second
            # Height: (voltage_span * 10 mm/mV + 10 mm margin) / 25.4
            fig_width = (total_time_span * speed_mm_s) / MM_PER_INCH
            paper_lead_h_mm = max(40.0, (voltage_span * gain_mm_mv) + 10.0)
            paper_lead_h_in = paper_lead_h_mm / MM_PER_INCH
            header_space_in = (15.0 / MM_PER_INCH) if show_header else (5.0 / MM_PER_INCH)
            fig_height = (paper_lead_h_in * n_plots) + header_space_in
        else:
            # Digital mode: Expanded for high-resolution monitors & notebooks
            fig_width = max(12.0, total_time_span * 1.35)
            digital_lead_h = max(3.2, 0.8 * voltage_span)
            header_space = 0.8 if show_header else 0.4
            fig_height = max(digital_lead_h * n_plots + header_space, 3.2)

    fig, axes = plt.subplots(
        n_plots, 1, figsize=(fig_width, fig_height), sharex=True, squeeze=False
    )
    axes_flat = axes.flatten()

    # Adaptive font scaling based on lead height and figure height
    effective_lead_height = fig_height / n_plots
    scale_factor = (
        min(1.2, max(0.65, effective_lead_height / 3.0))
        if not is_paper
        else min(1.0, max(0.70, effective_lead_height / 2.0))
    )

    label_font_sz = 10.0 * scale_factor if not is_paper else 8.5
    badge_font_sz = 10.5 * scale_factor if not is_paper else 9.0
    rr_font_sz = max(6.0, 7.5 * scale_factor) if not is_paper else 6.5
    cal_font_sz = max(6.5, 8.5 * scale_factor) if not is_paper else 7.5

    for idx, lead_i in enumerate(selected_leads):
        ax = axes_flat[idx]
        lead_name = sliced_sig.lead_names[lead_i]
        lead_data = sliced_sig.get_lead(lead_i)

        # Draw clinical millimeter grid with sparse tick labels
        draw_clinical_grid(
            ax=ax,
            t_min=t_min,
            t_max=t_max,
            v_min=v_min,
            v_max=v_max,
            style_dict=style,
            time_tick_step=time_tick_step,
            voltage_tick_step=voltage_tick_step,
            sparse_ticks=sparse_ticks,
        )

        # Draw Calibration Pulse (1 mV x 0.2s = 10 mm x 5 mm)
        if show_calibration_pulse:
            cal_t, cal_v = generate_calibration_pulse(
                sampling_rate=sliced_sig.sampling_rate,
                start_time=-cal_offset,
                pulse_width=0.20,
                pulse_height=1.0,
            )
            ax.plot(
                cal_t,
                cal_v,
                color=style["signal_color"],
                linewidth=style["signal_lw"],
                solid_capstyle="round",
            )
            ax.text(
                -cal_offset + 0.10,
                1.08,
                "1 mV",
                fontsize=cal_font_sz,
                fontweight="bold",
                color=style["text_color"],
                ha="center",
                va="bottom",
            )

        # Plot ECG Signal Trace
        ax.plot(
            t_vector,
            lead_data,
            color=style["signal_color"],
            linewidth=style["signal_lw"],
            solid_capstyle="round",
            label=lead_name,
        )

        # Lead Label on left
        ax.text(
            0.015,
            0.88,
            f"Lead: {lead_name}",
            transform=ax.transAxes,
            fontsize=badge_font_sz,
            fontweight="bold",
            color=style["text_color"],
            va="top",
            bbox=dict(
                boxstyle="round,pad=0.2",
                facecolor=style["bg_color"],
                edgecolor=style["major_color"],
                alpha=0.9,
            ),
        )

        # Plot R-Peak Annotations
        if r_peaks is not None and len(r_peaks) > 0:
            r_times = []
            r_amps = []
            for rp in r_peaks:
                rp_time = rp / signal.sampling_rate - start_time
                if 0.0 <= rp_time <= t_max:
                    sample_idx = int(round(rp_time * sliced_sig.sampling_rate))
                    if 0 <= sample_idx < len(lead_data):
                        r_times.append(rp_time)
                        r_amps.append(lead_data[sample_idx])

            if r_times:
                r_times_arr = np.array(r_times)
                r_amps_arr = np.array(r_amps)
                marker_offset = 0.12 * (v_max - v_min) / 3.0
                ax.scatter(
                    r_times_arr,
                    r_amps_arr + marker_offset,
                    marker="v",
                    color="#dc2626",
                    s=max(20, 38 * scale_factor),
                    zorder=5,
                    label="R-Peak",
                )

                # Draw RR interval measurements between consecutive beats
                if len(r_times) >= 2:
                    for j in range(len(r_times) - 1):
                        t1, t2 = r_times[j], r_times[j + 1]
                        rr_sec = t2 - t1
                        inst_hr = 60.0 / rr_sec if rr_sec > 0 else 0
                        mid_t = (t1 + t2) / 2.0
                        ax.text(
                            mid_t,
                            v_max - (0.15 * (v_max - v_min) / 3.0),
                            f"{int(round(rr_sec * 1000))} ms\n({int(round(inst_hr))} bpm)",
                            fontsize=rr_font_sz,
                            color="#991b1b",
                            ha="center",
                            va="top",
                            fontfamily="monospace",
                            bbox=dict(
                                boxstyle="square,pad=0.1",
                                facecolor="#ffffff",
                                edgecolor="#f87171",
                                alpha=0.8,
                            ),
                        )

        # Plot P-Q-R-S-T Wave Annotations if provided
        if waves is not None:
            wave_colors = {"P": "#2563eb", "Q": "#d97706", "S": "#7c3aed", "T": "#059669"}
            for wave_name, wave_indices in waves.items():
                if wave_name in wave_colors:
                    w_times = []
                    w_amps = []
                    for wi in wave_indices:
                        wi_time = wi / signal.sampling_rate - start_time
                        if 0.0 <= wi_time <= t_max:
                            s_idx = int(round(wi_time * sliced_sig.sampling_rate))
                            if 0 <= s_idx < len(lead_data):
                                w_times.append(wi_time)
                                w_amps.append(lead_data[s_idx])
                    if w_times:
                        ax.scatter(
                            w_times,
                            w_amps,
                            color=wave_colors[wave_name],
                            s=max(16, 24 * scale_factor),
                            zorder=4,
                            label=f"{wave_name}-Wave",
                        )

        # Custom Annotations
        if annotations:
            for ann in annotations:
                ann_time = ann.get("time", 0.0) - start_time
                ann_text = ann.get("text", "")
                if 0.0 <= ann_time <= t_max:
                    ax.axvline(
                        x=ann_time, color="#dc2626", linestyle="--", linewidth=0.9, alpha=0.8
                    )
                    ax.text(
                        ann_time,
                        v_min + 0.15,
                        f" {ann_text}",
                        fontsize=max(6.0, 7.5 * scale_factor),
                        fontweight="bold",
                        color="#dc2626",
                        rotation=90,
                        va="bottom",
                    )

        # Axis styling
        ax.set_ylabel(
            "Voltage (mV)", fontsize=label_font_sz, color=style["text_color"], fontweight="medium"
        )
        ax.tick_params(
            axis="both",
            which="major",
            labelsize=max(7.0, 8.0 * scale_factor),
            colors=style["text_color"],
        )

    # Bottom axis label
    axes_flat[-1].set_xlabel(
        "Time (seconds)",
        fontsize=label_font_sz + 0.5,
        color=style["text_color"],
        fontweight="medium",
    )

    # Medical Header Banner on Top
    if show_header:
        rec_name = signal.record_name if signal.record_name else "ECG_RECORD"
        pat_id = signal.patient_id if signal.patient_id else "ANONYMOUS"
        approx_hr = int(round(signal.metadata.get("heart_rate_bpm", 72))) if signal.metadata else 72

        header_text = (
            f"PATIENT ID: {pat_id}  |  RECORD: {rec_name}  |  "
            f"EST. HR: ~{approx_hr} bpm  |  SPEED: {speed_mm_s:.0f} mm/s  |  "
            f"GAIN: {gain_mm_mv:.0f} mm/mV  |  1 mm = 0.04s / 0.1mV"
        )

        if title:
            fig_title = f"{title}\n{header_text}"
        else:
            fig_title = header_text

        title_lines = fig_title.count("\n") + 1
        needed_top_in = 0.30 + (0.18 * title_lines)
        top_fraction = max(0.68, 1.0 - (needed_top_in / fig_height))

        fig.suptitle(
            fig_title,
            fontsize=max(7.5, min(10.5, 9.5 * scale_factor)),
            fontweight="bold",
            fontfamily="monospace",
            color=style["text_color"],
            y=0.985,
            va="top",
        )
        plt.subplots_adjust(
            top=top_fraction, bottom=max(0.08, 0.40 / fig_height), left=0.06, right=0.98
        )
    else:
        if title:
            fig.suptitle(
                title,
                fontsize=max(8.5, 10.5 * scale_factor),
                fontweight="bold",
                color=style["text_color"],
            )
            plt.subplots_adjust(top=0.90, bottom=0.10, left=0.06, right=0.98)
        else:
            plt.subplots_adjust(top=0.96, bottom=0.10, left=0.06, right=0.98)

    if save_path:
        fig.savefig(save_path, dpi=300, bbox_inches="tight")

    return fig, axes_flat[0] if n_plots == 1 else axes

plot_12lead_clinical(signal, duration=2.5, display_mode='paper', paper_size='letter', speed_mm_s=25.0, gain_mm_mv=10.0, grid_style='clinical_pink', voltage_range=(-1.5, 2.0), ylim=None, plot_height=None, figsize=None, time_tick_step=1.0, voltage_tick_step=1.0, sparse_ticks=True, rhythm_lead='II', show_header=True, save_path=None)

Plot standard clinical 12-lead ECG format (3 rows x 4 columns + 1 continuous rhythm strip at bottom).

Layout: - Col 1: I, II, III - Col 2: aVR, aVL, aVF - Col 3: V1, V2, V3 - Col 4: V4, V5, V6 - Bottom row: Continuous rhythm strip (default Lead II).

Parameters:

Name Type Description Default
signal ECGSignal

ECGSignal instance containing 12 leads.

required
duration float

Duration of 3x4 lead blocks in seconds (default: 2.5s).

2.5
display_mode str

'paper' (1:1 physical sheet: US Letter 11"x8.5" or A4 11.69"x8.27") or 'digital' (expanded 18"x10" landscape for monitors/slides).

'paper'
paper_size str

'letter' (11.0" x 8.5") or 'a4' (11.69" x 8.27").

'letter'
speed_mm_s float

Standard paper speed (25.0 mm/s).

25.0
gain_mm_mv float

Voltage gain (10.0 mm/mV).

10.0
grid_style str

'clinical_pink', 'clinical_red', 'clinical_gray', 'dark_telemetry'.

'clinical_pink'
voltage_range Optional[Tuple[float, float]]

Vertical limits in mV (default (-1.5, 2.0)).

(-1.5, 2.0)
ylim Optional[Tuple[float, float]]

Alias for voltage_range.

None
plot_height Optional[float]

Total figure height in inches.

None
figsize Optional[Tuple[float, float]]

Optional (width, height) in inches.

None
time_tick_step Optional[float]

Step in seconds for sparse time labels.

1.0
voltage_tick_step Optional[float]

Step in mV for sparse voltage labels.

1.0
sparse_ticks bool

If True, renders uncluttered labels at clean intervals.

True
rhythm_lead str

Lead name to use for full-width bottom rhythm strip.

'II'
show_header bool

Whether to display medical header banner.

True
save_path Optional[str]

Optional output image path.

None

Returns:

Type Description
Tuple[Figure, ndarray]

(fig, axes_array)

Source code in ecg_sdk/visualization/plotter.py
def plot_12lead_clinical(
    signal: ECGSignal,
    duration: float = 2.5,
    display_mode: str = "paper",
    paper_size: str = "letter",
    speed_mm_s: float = 25.0,
    gain_mm_mv: float = 10.0,
    grid_style: str = "clinical_pink",
    voltage_range: Optional[Tuple[float, float]] = (-1.5, 2.0),
    ylim: Optional[Tuple[float, float]] = None,
    plot_height: Optional[float] = None,
    figsize: Optional[Tuple[float, float]] = None,
    time_tick_step: Optional[float] = 1.0,
    voltage_tick_step: Optional[float] = 1.0,
    sparse_ticks: bool = True,
    rhythm_lead: str = "II",
    show_header: bool = True,
    save_path: Optional[str] = None,
) -> Tuple[plt.Figure, np.ndarray]:
    """
    Plot standard clinical 12-lead ECG format (3 rows x 4 columns + 1 continuous rhythm strip at bottom).

    Layout:
    - Col 1: I, II, III
    - Col 2: aVR, aVL, aVF
    - Col 3: V1, V2, V3
    - Col 4: V4, V5, V6
    - Bottom row: Continuous rhythm strip (default Lead II).

    Args:
        signal: ECGSignal instance containing 12 leads.
        duration: Duration of 3x4 lead blocks in seconds (default: 2.5s).
        display_mode: 'paper' (1:1 physical sheet: US Letter 11"x8.5" or A4 11.69"x8.27")
                      or 'digital' (expanded 18"x10" landscape for monitors/slides).
        paper_size: 'letter' (11.0" x 8.5") or 'a4' (11.69" x 8.27").
        speed_mm_s: Standard paper speed (25.0 mm/s).
        gain_mm_mv: Voltage gain (10.0 mm/mV).
        grid_style: 'clinical_pink', 'clinical_red', 'clinical_gray', 'dark_telemetry'.
        voltage_range: Vertical limits in mV (default (-1.5, 2.0)).
        ylim: Alias for voltage_range.
        plot_height: Total figure height in inches.
        figsize: Optional (width, height) in inches.
        time_tick_step: Step in seconds for sparse time labels.
        voltage_tick_step: Step in mV for sparse voltage labels.
        sparse_ticks: If True, renders uncluttered labels at clean intervals.
        rhythm_lead: Lead name to use for full-width bottom rhythm strip.
        show_header: Whether to display medical header banner.
        save_path: Optional output image path.

    Returns:
        (fig, axes_array)
    """
    style = GRID_STYLES.get(grid_style, GRID_STYLES["clinical_pink"])
    canonical_matrix = [
        ["I", "aVR", "V1", "V4"],
        ["II", "aVL", "V2", "V5"],
        ["III", "aVF", "V3", "V6"],
    ]

    v_limits = ylim or voltage_range or (-1.5, 2.0)
    v_min, v_max = v_limits

    is_paper = str(display_mode).lower().strip() == "paper"

    if figsize is not None:
        fig_w, fig_h = figsize
    elif plot_height is not None:
        fig_w = 11.0 if is_paper else 18.0
        fig_h = float(plot_height)
    else:
        if is_paper:
            sheet_dim = PAPER_SHEET_SIZES.get(paper_size.lower(), PAPER_SHEET_SIZES["letter"])
            fig_w, fig_h = sheet_dim
        else:
            fig_w, fig_h = (18.0, 10.0)

    scale_factor = min(1.2, max(0.65, fig_h / 9.0))

    fig = plt.figure(figsize=(fig_w, fig_h))
    gs = fig.add_gridspec(4, 4, height_ratios=[1, 1, 1, 1.2], hspace=0.35, wspace=0.15)

    lead_axes = []
    t_sec = min(duration, signal.duration)

    for row in range(3):
        for col in range(4):
            lead_name = canonical_matrix[row][col]
            ax = fig.add_subplot(gs[row, col])
            lead_axes.append(ax)

            if lead_name in signal.lead_names:
                lead_data = signal.get_lead(lead_name)
                n_samp = int(round(t_sec * signal.sampling_rate))
                t_vec = np.arange(n_samp) / signal.sampling_rate
                sig_chunk = lead_data[:n_samp]

                draw_clinical_grid(
                    ax=ax,
                    t_min=-0.3,
                    t_max=t_sec,
                    v_min=v_min,
                    v_max=v_max,
                    style_dict=style,
                    time_tick_step=time_tick_step,
                    voltage_tick_step=voltage_tick_step,
                    sparse_ticks=sparse_ticks,
                )

                # Calibration pulse
                cal_t, cal_v = generate_calibration_pulse(signal.sampling_rate, -0.3, 0.2, 1.0)
                ax.plot(cal_t, cal_v, color=style["signal_color"], linewidth=style["signal_lw"])

                # Signal
                ax.plot(t_vec, sig_chunk, color=style["signal_color"], linewidth=style["signal_lw"])

                # Lead Label
                ax.text(
                    0.03,
                    0.82,
                    lead_name,
                    transform=ax.transAxes,
                    fontsize=(
                        max(7.5, 9.5 * scale_factor) if is_paper else max(8.5, 10.5 * scale_factor)
                    ),
                    fontweight="bold",
                    color=style["text_color"],
                    bbox=dict(
                        boxstyle="round,pad=0.2",
                        facecolor=style["bg_color"],
                        edgecolor=style["major_color"],
                        alpha=0.85,
                    ),
                )
            else:
                ax.text(
                    0.5, 0.5, f"Lead {lead_name} N/A", ha="center", va="center", color="#94a3b8"
                )
                draw_clinical_grid(ax, 0, t_sec, v_min, v_max, style, sparse_ticks=sparse_ticks)

    # Bottom Rhythm Strip (Full 10s or available duration)
    rhythm_ax = fig.add_subplot(gs[3, :])
    rhythm_t_sec = min(10.0, signal.duration)
    rhythm_n_samp = int(round(rhythm_t_sec * signal.sampling_rate))
    rhythm_t_vec = np.arange(rhythm_n_samp) / signal.sampling_rate

    target_lead = rhythm_lead if rhythm_lead in signal.lead_names else signal.lead_names[0]
    rhythm_data = signal.get_lead(target_lead)[:rhythm_n_samp]

    draw_clinical_grid(
        ax=rhythm_ax,
        t_min=-0.3,
        t_max=rhythm_t_sec,
        v_min=v_min,
        v_max=v_max,
        style_dict=style,
        time_tick_step=time_tick_step,
        voltage_tick_step=voltage_tick_step,
        sparse_ticks=sparse_ticks,
    )
    cal_t, cal_v = generate_calibration_pulse(signal.sampling_rate, -0.3, 0.2, 1.0)
    rhythm_ax.plot(cal_t, cal_v, color=style["signal_color"], linewidth=style["signal_lw"])
    rhythm_ax.plot(
        rhythm_t_vec, rhythm_data, color=style["signal_color"], linewidth=style["signal_lw"]
    )

    rhythm_ax.text(
        0.01,
        0.82,
        f"Rhythm Strip ({target_lead})",
        transform=rhythm_ax.transAxes,
        fontsize=max(7.5, 9.5 * scale_factor) if is_paper else max(8.5, 10.5 * scale_factor),
        fontweight="bold",
        color=style["text_color"],
        bbox=dict(
            boxstyle="round,pad=0.2",
            facecolor=style["bg_color"],
            edgecolor=style["major_color"],
            alpha=0.85,
        ),
    )
    rhythm_ax.set_xlabel(
        "Time (seconds)",
        fontsize=max(7.5, 9.5 * scale_factor) if is_paper else max(8.5, 10.5 * scale_factor),
        color=style["text_color"],
    )

    # Header
    if show_header:
        header = (
            f"12-LEAD CLINICAL ECG REPORT  |  SPEED: {speed_mm_s:.0f} mm/s  |  "
            f"GAIN: {gain_mm_mv:.0f} mm/mV  |  1 mm = 0.04s / 0.1mV"
        )
        needed_top_in = 0.50 if is_paper else 0.55
        top_fraction = max(0.72, 1.0 - (needed_top_in / fig_h))
        fig.suptitle(
            header,
            fontsize=max(8.0, 10.5 * scale_factor) if is_paper else max(9.0, 12.0 * scale_factor),
            fontweight="bold",
            fontfamily="monospace",
            color=style["text_color"],
            y=0.985,
        )
        plt.subplots_adjust(top=top_fraction, bottom=0.08, left=0.05, right=0.98)
    else:
        plt.subplots_adjust(top=0.96, bottom=0.08, left=0.05, right=0.98)

    if save_path:
        fig.savefig(save_path, dpi=300, bbox_inches="tight")

    return fig, np.array(lead_axes)

draw_clinical_grid(ax, t_min, t_max, v_min, v_max, style_dict, time_tick_step=1.0, voltage_tick_step=0.5, sparse_ticks=True)

Draw authentic clinical ECG millimeter grid lines onto a Matplotlib Axes.

Grid Specification: - Time axis (X): Minor grid = 0.04 s (1 mm at 25 mm/s) Major grid = 0.20 s (5 mm at 25 mm/s = 5 small squares) - Voltage axis (Y): Minor grid = 0.10 mV (1 mm at 10 mm/mV) Major grid = 0.50 mV (5 mm at 10 mm/mV = 5 small squares)

Source code in ecg_sdk/visualization/plotter.py
def draw_clinical_grid(
    ax: plt.Axes,
    t_min: float,
    t_max: float,
    v_min: float,
    v_max: float,
    style_dict: Dict[str, Any],
    time_tick_step: Optional[float] = 1.0,
    voltage_tick_step: Optional[float] = 0.5,
    sparse_ticks: bool = True,
) -> None:
    """
    Draw authentic clinical ECG millimeter grid lines onto a Matplotlib Axes.

    Grid Specification:
    - Time axis (X):
        Minor grid = 0.04 s (1 mm at 25 mm/s)
        Major grid = 0.20 s (5 mm at 25 mm/s = 5 small squares)
    - Voltage axis (Y):
        Minor grid = 0.10 mV (1 mm at 10 mm/mV)
        Major grid = 0.50 mV (5 mm at 10 mm/mV = 5 small squares)
    """
    ax.set_facecolor(style_dict["bg_color"])

    # Minor grid lines: 0.04s x, 0.10mV y
    ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.04))
    ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.10))

    # Major grid lines: 0.20s x, 0.50mV y
    ax.xaxis.set_major_locator(ticker.MultipleLocator(0.20))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(0.50))

    # Sparse Tick Formatting (Clean, uncrowded labels at clean integer / half-integer intervals)
    if sparse_ticks:
        t_step = (
            time_tick_step
            if time_tick_step is not None
            else (1.0 if (t_max - t_min) >= 3.0 else 0.5)
        )
        v_step = voltage_tick_step if voltage_tick_step is not None else 0.5
        ax.xaxis.set_major_formatter(
            make_sparse_formatter(t_step, decimals=1 if t_step < 1.0 else 0)
        )
        ax.yaxis.set_major_formatter(
            make_sparse_formatter(v_step, decimals=1 if v_step < 1.0 else 0)
        )

    ax.grid(
        True,
        which="minor",
        color=style_dict["minor_color"],
        linestyle="-",
        linewidth=style_dict["minor_lw"],
        alpha=style_dict["minor_alpha"],
    )
    ax.grid(
        True,
        which="major",
        color=style_dict["major_color"],
        linestyle="-",
        linewidth=style_dict["major_lw"],
        alpha=style_dict["major_alpha"],
    )

    ax.set_xlim(t_min, t_max)
    ax.set_ylim(v_min, v_max)

    # Clean borders
    for spine in ax.spines.values():
        spine.set_color(style_dict["border_color"])
        spine.set_linewidth(1.0)

generate_calibration_pulse(sampling_rate, start_time=0.0, pulse_width=0.2, pulse_height=1.0)

Generate standard 1 mV calibration pulse (0.2s duration = 5mm width x 10mm height).

Source code in ecg_sdk/visualization/plotter.py
def generate_calibration_pulse(
    sampling_rate: float,
    start_time: float = 0.0,
    pulse_width: float = 0.20,
    pulse_height: float = 1.0,
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Generate standard 1 mV calibration pulse (0.2s duration = 5mm width x 10mm height).
    """
    pad_time = 0.05
    total_time = pad_time * 2 + pulse_width
    n_samples = int(round(total_time * sampling_rate))
    t = np.linspace(start_time, start_time + total_time, n_samples)
    v = np.zeros(n_samples)

    start_pulse_idx = int(round(pad_time * sampling_rate))
    end_pulse_idx = start_pulse_idx + int(round(pulse_width * sampling_rate))
    v[start_pulse_idx:end_pulse_idx] = pulse_height

    return t, v