{"spec_id":"line-growth-percentile","library":"plotly","language":"python","code":"\"\"\" anyplot.ai\nline-growth-percentile: Pediatric Growth Chart with Percentile Curves\nLibrary: plotly 6.8.0 | Python 3.13.14\nQuality: 91/100 | Updated: 2026-06-20\n\"\"\"\n\nimport os\nimport sys\n\n\n# Prevent this file (plotly.py) from shadowing the installed plotly package\n_this_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if not p or os.path.abspath(p) != _this_dir]\n\nimport numpy as np\nimport plotly.graph_objects as go\n\n\n# Theme-adaptive chrome — Imprint palette\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\"\nGRID = \"rgba(26,26,23,0.15)\" if THEME == \"light\" else \"rgba(240,239,232,0.15)\"\n\n# Imprint palette position 1 — patient overlay (primary data series)\nPATIENT_COLOR = \"#009E73\"\n\n# Data — WHO-style weight-for-age reference for boys (0–36 months)\nnp.random.seed(42)\nage_months = np.arange(0, 37, 1)\n\n# Synthetic reference curves approximating WHO weight-for-age boys (z-score multipliers)\nmedian = 3.3 + 0.7 * age_months - 0.008 * age_months**2 + 0.00005 * age_months**3\nsd = 0.5 + 0.03 * age_months\n\npercentile_3 = median - 1.881 * sd\npercentile_10 = median - 1.282 * sd\npercentile_25 = median - 0.674 * sd\npercentile_50 = median\npercentile_75 = median + 0.674 * sd\npercentile_90 = median + 1.282 * sd\npercentile_97 = median + 1.881 * sd\n\n# Individual patient — healthy boy tracked at well-child visits\npatient_ages = np.array([0, 1, 2, 4, 6, 9, 12, 15, 18, 24, 30, 36])\npatient_weights = np.array([3.5, 4.1, 4.8, 6.1, 7.2, 8.8, 10.3, 11.7, 13.0, 15.6, 17.7, 19.4])\n\n# Graduated blue fills — semantic exception: spec requires blue tones for boys' chart\n# Increased opacity vs previous for better band visibility\nband_fills = [\n    \"rgba(30, 80, 140, 0.42)\",  # P3–P10 (outer edge)\n    \"rgba(50, 110, 170, 0.35)\",  # P10–P25\n    \"rgba(80, 145, 210, 0.30)\",  # P25–P50\n    \"rgba(80, 145, 210, 0.30)\",  # P50–P75\n    \"rgba(50, 110, 170, 0.35)\",  # P75–P90\n    \"rgba(30, 80, 140, 0.42)\",  # P90–P97 (outer edge)\n]\n\n# Per-trace line colors (7 entries: P3, P10, P25, P50, P75, P90, P97)\nband_line_colors = [\n    \"rgba(30, 80, 140, 0.55)\",  # P3\n    \"rgba(30, 80, 140, 0.55)\",  # P10\n    \"rgba(50, 110, 170, 0.45)\",  # P25\n    \"rgba(25, 70, 130, 0.88)\",  # P50 — emphasized median\n    \"rgba(50, 110, 170, 0.45)\",  # P75\n    \"rgba(30, 80, 140, 0.55)\",  # P90\n    \"rgba(30, 80, 140, 0.55)\",  # P97\n]\nband_widths = [1.0, 1.0, 1.0, 2.5, 1.0, 1.0, 1.0]  # P50 thicker\n\n# Percentile data in bottom-to-top order for tonexty stacking\npercentile_stack = [\n    (percentile_3, \"P3\", None),\n    (percentile_10, \"P10\", band_fills[0]),\n    (percentile_25, \"P25\", band_fills[1]),\n    (percentile_50, \"P50\", band_fills[2]),\n    (percentile_75, \"P75\", band_fills[3]),\n    (percentile_90, \"P90\", band_fills[4]),\n    (percentile_97, \"P97\", band_fills[5]),\n]\n\nfig = go.Figure()\n\n# Percentile bands — idiomatic tonexty fill stacking\nfor i, (pct_data, pct_label, fill_color) in enumerate(percentile_stack):\n    fig.add_trace(\n        go.Scatter(\n            x=age_months,\n            y=pct_data,\n            mode=\"lines\",\n            line={\"color\": band_line_colors[i], \"width\": band_widths[i]},\n            fill=\"tonexty\" if fill_color else None,\n            fillcolor=fill_color,\n            showlegend=False,\n            name=pct_label,\n            customdata=np.column_stack([np.full_like(age_months, float(pct_label[1:])), pct_data]),\n            hovertemplate=(\n                \"<b>P%{customdata[0]:.0f}</b><br>Age: %{x} months<br>Weight: %{customdata[1]:.1f} kg<extra></extra>\"\n            ),\n        )\n    )\n\n# Right-margin percentile labels with anti-crowding spacing\nlabel_data = [\n    (percentile_3[-1], \"P3\"),\n    (percentile_10[-1], \"P10\"),\n    (percentile_25[-1], \"P25\"),\n    (percentile_50[-1], \"P50\"),\n    (percentile_75[-1], \"P75\"),\n    (percentile_90[-1], \"P90\"),\n    (percentile_97[-1], \"P97\"),\n]\n# Increased min_gap from 0.55 → 0.80 to fix crowding at lower percentiles\nmin_gap = 0.80\nlabel_positions = [y for y, _ in label_data]\nfor i in range(1, len(label_positions)):\n    if label_positions[i] - label_positions[i - 1] < min_gap:\n        label_positions[i] = label_positions[i - 1] + min_gap\n\nfor (_, pct_label), y_pos in zip(label_data, label_positions, strict=False):\n    is_median = pct_label == \"P50\"\n    fig.add_annotation(\n        x=37.3,\n        y=y_pos,\n        text=f\"<b>{pct_label}</b>\" if is_median else pct_label,\n        showarrow=False,\n        font={\n            \"size\": 11 if is_median else 10,\n            \"color\": \"rgba(25, 70, 130, 0.95)\" if is_median else \"rgba(50, 100, 160, 0.80)\",\n            \"family\": \"Arial\",\n        },\n        xanchor=\"left\",\n    )\n\n# Patient data — Imprint position 1 (green) for strong contrast against blue reference bands\nfig.add_trace(\n    go.Scatter(\n        x=patient_ages,\n        y=patient_weights,\n        mode=\"lines+markers\",\n        line={\"color\": PATIENT_COLOR, \"width\": 3.0, \"shape\": \"spline\"},\n        marker={\"size\": 10, \"color\": PATIENT_COLOR, \"line\": {\"color\": PAGE_BG, \"width\": 2}, \"symbol\": \"circle\"},\n        name=\"Patient (Boy)\",\n        showlegend=True,\n        customdata=np.column_stack([patient_ages, patient_weights]),\n        hovertemplate=(\n            \"<b>Patient Visit</b><br>Age: %{customdata[0]:.0f} months<br>Weight: %{customdata[1]:.1f} kg<extra></extra>\"\n        ),\n    )\n)\n\n# Clinical annotation — percentile position at 36 months\nfig.add_annotation(\n    x=33,\n    y=patient_weights[-1] + 1.0,\n    text=\"<b>~25th percentile</b><br>at 36 months\",\n    showarrow=True,\n    arrowhead=2,\n    arrowsize=1,\n    arrowwidth=1.5,\n    arrowcolor=PATIENT_COLOR,\n    ax=-60,\n    ay=-40,\n    font={\"size\": 10, \"color\": PATIENT_COLOR, \"family\": \"Arial\"},\n    align=\"center\",\n    bordercolor=PATIENT_COLOR,\n    borderwidth=1,\n    borderpad=5,\n    bgcolor=ELEVATED_BG,\n)\n\n# Title — font scaled for long string (formula: round(16 * 67 / len(title)))\ntitle_text = \"Weight-for-Age Boys (0–36 months) · line-growth-percentile · python · plotly · anyplot.ai\"\ntitle_fontsize = max(10, round(16 * 67 / len(title_text)))\n\nfig.update_layout(\n    autosize=False,\n    paper_bgcolor=PAGE_BG,\n    plot_bgcolor=PAGE_BG,\n    font={\"color\": INK, \"family\": \"Arial\"},\n    template=\"plotly_white\",\n    title={\n        \"text\": title_text,\n        \"font\": {\"size\": title_fontsize, \"color\": INK},\n        \"x\": 0.5,\n        \"xanchor\": \"center\",\n        \"y\": 0.98,\n        \"yanchor\": \"top\",\n    },\n    xaxis={\n        \"title\": {\"text\": \"Age (months)\", \"font\": {\"size\": 12, \"color\": INK}, \"standoff\": 10},\n        \"tickfont\": {\"size\": 10, \"color\": INK_SOFT},\n        \"range\": [-0.5, 40],\n        \"dtick\": 3,\n        \"showgrid\": True,\n        \"gridwidth\": 1,\n        \"gridcolor\": GRID,\n        \"zeroline\": False,\n        \"linecolor\": INK_SOFT,\n        \"tickcolor\": INK_SOFT,\n    },\n    yaxis={\n        \"title\": {\"text\": \"Weight (kg)\", \"font\": {\"size\": 12, \"color\": INK}, \"standoff\": 10},\n        \"tickfont\": {\"size\": 10, \"color\": INK_SOFT},\n        \"range\": [0, 25],\n        \"showgrid\": True,\n        \"gridwidth\": 1,\n        \"gridcolor\": GRID,\n        \"zeroline\": False,\n        \"linecolor\": INK_SOFT,\n        \"tickcolor\": INK_SOFT,\n    },\n    legend={\n        \"font\": {\"size\": 10, \"color\": INK_SOFT},\n        \"x\": 0.02,\n        \"y\": 0.98,\n        \"bgcolor\": ELEVATED_BG,\n        \"bordercolor\": INK_SOFT,\n        \"borderwidth\": 1,\n    },\n    hovermode=\"closest\",\n    hoverlabel={\"font\": {\"size\": 10}, \"bgcolor\": ELEVATED_BG},\n    margin={\"l\": 80, \"r\": 95, \"t\": 60, \"b\": 65},\n)\n\n# Save — 3200×1800 landscape (width=800, height=450, scale=4)\nfig.write_image(f\"plot-{THEME}.png\", width=800, height=450, scale=4)\nfig.write_html(f\"plot-{THEME}.html\", include_plotlyjs=\"cdn\", config={\"displayModeBar\": True, \"scrollZoom\": True})\n"}