{"spec_id":"ecg-twelve-lead","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\necg-twelve-lead: ECG/EKG 12-Lead Waveform Display\nLibrary: plotnine 0.15.7 | Python 3.13.13\nQuality: 90/100 | Updated: 2026-06-17\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    coord_cartesian,\n    element_blank,\n    element_line,\n    element_rect,\n    element_text,\n    facet_wrap,\n    geom_line,\n    geom_segment,\n    geom_text,\n    ggplot,\n    labs,\n    scale_x_continuous,\n    scale_y_continuous,\n    theme,\n)\n\n\n# Theme-adaptive chrome (see prompts/default-style-guide.md)\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\n# ECG-paper red grid — the iconic clinical convention (light red/pink), kept\n# theme-adaptive so the warm cream / warm black page surfaces stay compliant.\nGRID_MAJOR = \"#D98C7A\" if THEME == \"light\" else \"#6B3A35\"\nGRID_MINOR = \"#EBC9BD\" if THEME == \"light\" else \"#3A2623\"\n\n# Trace in Imprint brand green (#009E73, palette position 1) — also the classic\n# bedside-monitor ECG colour, so the brand-first rule and the domain align.\nTRACE = \"#009E73\"\n\n# Data — synthetic normal sinus rhythm via a Gaussian P-QRS-T pulse model\nnp.random.seed(42)\n\nsampling_rate = 500\nduration = 2.5\nt = np.linspace(0, duration, int(sampling_rate * duration), endpoint=False)\nn_samples = len(t)\n\nhr_bpm = 72\nhr_interval = 60.0 / hr_bpm\nbeat_centers = np.arange(hr_interval * 0.35, duration, hr_interval)\n\n\ndef _gauss(t_arr, center, width, amplitude):\n    return amplitude * np.exp(-((t_arr - center) ** 2) / (2 * width**2))\n\n\ndef _ecg_beat(t_arr, bc, hri, p_amp=0.15, p_width=0.025, t_amp=0.30, t_width=0.04):\n    p = _gauss(t_arr, bc - 0.16 * hri, p_width, p_amp)\n    q = _gauss(t_arr, bc - 0.04 * hri, 0.007, -0.12)\n    r = _gauss(t_arr, bc, 0.007, 1.2)\n    s = _gauss(t_arr, bc + 0.025 * hri, 0.007, -0.20)\n    st = _gauss(t_arr, bc + 0.08 * hri, 0.02, 0.03)\n    tw = _gauss(t_arr, bc + 0.22 * hri, t_width, t_amp)\n    return p + q + r + s + st + tw\n\n\n# Lead-specific morphology: (scale, p_amp, p_width, t_amp, t_width)\nlead_params = {\n    \"I\": (0.55, 0.12, 0.025, 0.25, 0.04),\n    \"II\": (1.0, 0.18, 0.028, 0.35, 0.045),\n    \"III\": (0.45, 0.08, 0.022, 0.18, 0.038),\n    \"aVR\": (-0.65, -0.10, 0.024, -0.22, 0.042),\n    \"aVL\": (0.25, 0.06, 0.020, 0.10, 0.035),\n    \"aVF\": (0.70, 0.14, 0.026, 0.28, 0.042),\n    \"V1\": (-0.75, 0.08, 0.020, -0.18, 0.038),\n    \"V2\": (-0.40, 0.10, 0.022, 0.12, 0.040),\n    \"V3\": (0.35, 0.12, 0.024, 0.22, 0.042),\n    \"V4\": (0.95, 0.15, 0.026, 0.32, 0.044),\n    \"V5\": (0.70, 0.13, 0.025, 0.28, 0.043),\n    \"V6\": (0.50, 0.11, 0.024, 0.22, 0.040),\n}\n\n# Standard clinical 3×4 grid order (3 rows, 4 columns)\n# Row 0: I, aVR, V1, V4 | Row 1: II, aVL, V2, V5 | Row 2: III, aVF, V3, V6\ngrid_order = [\"I\", \"aVR\", \"V1\", \"V4\", \"II\", \"aVL\", \"V2\", \"V5\", \"III\", \"aVF\", \"V3\", \"V6\"]\n\nframes = []\nfor lead_name in grid_order:\n    scale, p_a, p_w, t_a, t_w = lead_params[lead_name]\n    signal = np.zeros_like(t)\n    for bc in beat_centers:\n        signal += scale * _ecg_beat(t, bc, hr_interval, p_amp=p_a, p_width=p_w, t_amp=t_a, t_width=t_w)\n    signal += np.random.normal(0, 0.008, n_samples)\n    frames.append(pd.DataFrame({\"time\": t, \"voltage\": signal, \"lead\": lead_name}))\n\ndf = pd.concat(frames, ignore_index=True)\ndf[\"lead\"] = pd.Categorical(df[\"lead\"], categories=grid_order, ordered=True)\n\n# Lead label positions (top-left of each facet)\nlabel_df = pd.DataFrame(\n    {\n        \"time\": [0.08] * 12,\n        \"voltage\": [1.38] * 12,\n        \"lead\": pd.Categorical(grid_order, categories=grid_order, ordered=True),\n        \"label\": grid_order,\n    }\n)\n\n# 1 mV calibration pulse via segments — shown in Lead I\n_cal_lead = pd.Categorical([\"I\"], categories=grid_order, ordered=True)\ncal_seg_df = pd.DataFrame(\n    {\n        \"x\": [0.0, 0.0, 0.05],\n        \"xend\": [0.0, 0.05, 0.05],\n        \"y\": [0.0, 1.0, 1.0],\n        \"yend\": [1.0, 1.0, 0.0],\n        \"lead\": pd.Categorical([\"I\"] * 3, categories=grid_order, ordered=True),\n    }\n)\ncal_label_df = pd.DataFrame({\"time\": [0.025], \"voltage\": [-0.28], \"lead\": _cal_lead, \"label\": [\"1 mV\"]})\n\n# Standard ECG paper: 25 mm/s → major lines every 0.2 s, minor every 0.04 s\nx_minor = np.arange(0, duration + 0.01, 0.04).tolist()\n# Vertical: 10 mm/mV → major every 0.5 mV, minor every 0.1 mV\ny_major = np.arange(-1.5, 1.6, 0.5).tolist()\ny_minor = np.arange(-1.5, 1.6, 0.1).tolist()\n# Show only 0.0, 0.5, 1.0, … on x-axis (grid lines at 0.2 s/0.04 s intervals remain)\nx_labels = np.arange(0, duration + 0.01, 0.5).tolist()\n\nplot = (\n    ggplot(df, aes(x=\"time\", y=\"voltage\"))\n    + geom_line(color=TRACE, size=0.9)\n    + geom_segment(aes(x=\"x\", xend=\"xend\", y=\"y\", yend=\"yend\"), data=cal_seg_df, color=INK, size=1.0, inherit_aes=False)\n    + geom_text(aes(label=\"label\"), data=label_df, size=5, ha=\"left\", va=\"top\", fontweight=\"bold\", color=INK)\n    + geom_text(aes(label=\"label\"), data=cal_label_df, size=3, ha=\"center\", va=\"top\", color=INK_SOFT)\n    + facet_wrap(\"lead\", ncol=4)\n    + scale_x_continuous(breaks=x_labels, minor_breaks=x_minor, expand=(0.01, 0.01))\n    + scale_y_continuous(breaks=y_major, minor_breaks=y_minor, expand=(0, 0))\n    + coord_cartesian(xlim=(0, duration), ylim=(-1.6, 1.6))\n    + labs(title=\"ecg-twelve-lead · python · plotnine · anyplot.ai\", x=\"Time (s)\", y=\"Voltage (mV)\")\n    + theme(\n        figure_size=(8, 4.5),\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG),\n        panel_grid_major_x=element_line(color=GRID_MAJOR, size=0.5),\n        panel_grid_major_y=element_line(color=GRID_MAJOR, size=0.5),\n        panel_grid_minor_x=element_line(color=GRID_MINOR, size=0.25),\n        panel_grid_minor_y=element_line(color=GRID_MINOR, size=0.25),\n        strip_background=element_blank(),\n        strip_text=element_blank(),\n        text=element_text(size=7, color=INK_SOFT),\n        axis_title=element_text(size=10, color=INK),\n        axis_text_x=element_text(size=8, color=INK_SOFT),\n        axis_text_y=element_text(size=7, color=INK_MUTED),\n        plot_title=element_text(size=13, weight=\"bold\", color=INK, margin={\"b\": 10}),\n        panel_spacing_x=0.04,\n        panel_spacing_y=0.05,\n        axis_ticks=element_blank(),\n    )\n)\n\n# Save\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\", verbose=False)\n"}