{"spec_id":"spirometry-flow-volume","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\nspirometry-flow-volume: Spirometry Flow-Volume Loop\nLibrary: plotnine 0.15.7 | Python 3.13.13\nQuality: 91/100 | Updated: 2026-06-17\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    annotate,\n    coord_cartesian,\n    element_blank,\n    element_line,\n    element_rect,\n    element_text,\n    geom_hline,\n    geom_path,\n    geom_point,\n    geom_ribbon,\n    geom_text,\n    ggplot,\n    guide_legend,\n    guides,\n    labs,\n    scale_color_manual,\n    scale_fill_manual,\n    scale_linetype_manual,\n    scale_x_continuous,\n    scale_y_continuous,\n    theme,\n    theme_minimal,\n)\n\n\n# Theme tokens (see prompts/default-style-guide.md \"Theme-adaptive Chrome\")\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\n\n# Imprint palette: measured loop is the brand green (first series); the predicted\n# normal loop is the violet second-series anchor; the deficit ribbon uses the amber\n# caution anchor; PEF focal point uses the matte-red semantic anchor.\nBRAND = \"#009E73\"  # Imprint position 1 — measured loop\nPREDICTED = \"#C475FD\"  # Imprint position 2 (violet) — predicted normal reference\nDEFICIT = \"#DDCC77\"  # amber anchor — caution / deficit\nPEF_RED = \"#AE3030\"  # Imprint position 5 (matte red) — PEF emphasis\n\n# Clinical parameters\nfvc, fev1, pef = 4.8, 3.6, 9.5\nfvc_pred, pef_pred = 5.2, 10.5\nn = 150\n\n# Measured loop data\nvol_exp_m = np.linspace(0, fvc, n)\nt_m = vol_exp_m / fvc\nk = 2.5\nflow_exp_m = pef * (4 * t_m * np.exp(-k * t_m) / (4 * (1 / k) * np.exp(-1))) * (1 - t_m**1.5)\nflow_exp_m[0] = 0\npeak_idx_m = np.argmax(flow_exp_m)\nflow_exp_m[:peak_idx_m] = np.linspace(0, flow_exp_m[peak_idx_m], peak_idx_m)\nflow_exp_m = flow_exp_m / flow_exp_m.max() * pef\n\nvol_insp_m = np.linspace(fvc, 0, n)\nflow_insp_m = -6.0 * np.sin(np.pi * np.linspace(0, 1, n))\nflow_insp_m[0] = 0\nflow_insp_m[-1] = 0\n\nvol_m = np.concatenate([vol_exp_m, vol_insp_m])\nflow_m = np.concatenate([flow_exp_m, flow_insp_m])\n\n# Predicted normal loop data\nvol_exp_p = np.linspace(0, fvc_pred, n)\nt_p = vol_exp_p / fvc_pred\nflow_exp_p = pef_pred * (4 * t_p * np.exp(-k * t_p) / (4 * (1 / k) * np.exp(-1))) * (1 - t_p**1.5)\nflow_exp_p[0] = 0\npeak_idx_p = np.argmax(flow_exp_p)\nflow_exp_p[:peak_idx_p] = np.linspace(0, flow_exp_p[peak_idx_p], peak_idx_p)\nflow_exp_p = flow_exp_p / flow_exp_p.max() * pef_pred\n\nvol_insp_p = np.linspace(fvc_pred, 0, n)\nflow_insp_p = -6.8 * np.sin(np.pi * np.linspace(0, 1, n))\nflow_insp_p[0] = 0\nflow_insp_p[-1] = 0\n\nvol_p = np.concatenate([vol_exp_p, vol_insp_p])\nflow_p = np.concatenate([flow_exp_p, flow_insp_p])\n\n# Ribbon: shaded deficit between measured and predicted expiratory limbs\nflow_pred_interp = np.interp(vol_exp_m, vol_exp_p, flow_exp_p)\ndf_ribbon = pd.DataFrame(\n    {\n        \"volume\": vol_exp_m,\n        \"flow_measured\": flow_exp_m,\n        \"flow_predicted\": flow_pred_interp,\n        \"fill_label\": \"Deficit vs predicted\",\n    }\n)\n\n# Main loop data\ndf = pd.concat(\n    [\n        pd.DataFrame({\"volume\": vol_m, \"flow\": flow_m, \"type\": \"Measured\"}),\n        pd.DataFrame({\"volume\": vol_p, \"flow\": flow_p, \"type\": \"Predicted normal\"}),\n    ],\n    ignore_index=True,\n)\n\n# PEF marker\npef_vol = vol_m[peak_idx_m]\npef_flow = flow_m[peak_idx_m]\ndf_pef = pd.DataFrame({\"volume\": [pef_vol], \"flow\": [pef_flow], \"label\": [f\"PEF = {pef:.1f} L/s\"]})\n\nclinical_text = f\"FVC = {fvc:.1f} L\\nFEV₁ = {fev1:.1f} L\\nPEF = {pef:.1f} L/s\\nFEV₁/FVC = {fev1 / fvc:.0%}\"\n\n# Plot\nplot = (\n    ggplot(df, aes(x=\"volume\", y=\"flow\", color=\"type\", linetype=\"type\"))\n    + geom_ribbon(\n        data=df_ribbon,\n        mapping=aes(x=\"volume\", ymin=\"flow_measured\", ymax=\"flow_predicted\", fill=\"fill_label\"),\n        inherit_aes=False,\n        alpha=0.30,\n        color=\"none\",\n    )\n    + geom_hline(yintercept=0, color=INK, size=0.5, alpha=0.55)\n    + geom_path(size=1.4, alpha=0.95, show_legend=True)\n    + geom_point(data=df_pef, mapping=aes(x=\"volume\", y=\"flow\"), color=PEF_RED, size=5, alpha=0.95, inherit_aes=False)\n    + geom_text(\n        data=df_pef,\n        mapping=aes(x=\"volume\", y=\"flow\", label=\"label\"),\n        color=PEF_RED,\n        size=5.2,\n        ha=\"left\",\n        va=\"bottom\",\n        nudge_x=0.35,\n        nudge_y=1.4,\n        fontweight=\"bold\",\n        inherit_aes=False,\n    )\n    + annotate(\n        \"label\",\n        x=0.25,\n        y=-3.6,\n        label=clinical_text,\n        size=5.0,\n        color=INK,\n        fill=ELEVATED_BG,\n        ha=\"left\",\n        va=\"top\",\n        label_size=0.3,\n        label_padding=0.4,\n    )\n    + scale_color_manual(name=\"Curve\", values={\"Measured\": BRAND, \"Predicted normal\": PREDICTED})\n    + scale_linetype_manual(name=\"Curve\", values={\"Measured\": \"solid\", \"Predicted normal\": \"dashed\"})\n    + scale_fill_manual(name=\" \", values={\"Deficit vs predicted\": DEFICIT})\n    + guides(\n        color=guide_legend(order=1),\n        linetype=guide_legend(order=1),\n        fill=guide_legend(order=2, override_aes={\"alpha\": 0.5}),\n    )\n    + scale_x_continuous(name=\"Volume (L)\", breaks=np.arange(0, 6, 1), minor_breaks=[])\n    + scale_y_continuous(name=\"Flow (L/s)\", breaks=np.arange(-8, 12, 2), minor_breaks=[])\n    + coord_cartesian(xlim=(-0.3, 6.0), ylim=(-8, 11.5))\n    + labs(title=\"spirometry-flow-volume · python · plotnine · anyplot.ai\")\n    + theme_minimal()\n    + theme(\n        figure_size=(8, 4.5),\n        plot_title=element_text(size=13, weight=\"bold\", color=INK),\n        axis_title=element_text(size=11, color=INK),\n        axis_text=element_text(size=9, color=INK_SOFT),\n        panel_grid_major=element_line(color=INK, size=0.3, alpha=0.15),\n        panel_grid_minor=element_blank(),\n        legend_title=element_text(size=10, weight=\"bold\", color=INK),\n        legend_text=element_text(size=9, color=INK_SOFT),\n        legend_position=(0.82, 0.76),\n        legend_box=\"vertical\",\n        legend_background=element_rect(fill=ELEVATED_BG + \"CC\", color=INK_SOFT, size=0.4),\n        legend_key=element_rect(fill=\"none\", color=\"none\"),\n        legend_key_width=26,\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG, color=\"none\"),\n    )\n)\n\n# Save\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\", verbose=False)\n"}