{"spec_id":"line-pca-variance-cumulative","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nline-pca-variance-cumulative: Cumulative Explained Variance for PCA Component Selection\nLibrary: bokeh 3.9.0 | Python 3.13.13\nQuality: 91/100 | Updated: 2026-05-29\n\"\"\"\n\nimport os\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import Band, ColumnDataSource, HoverTool, Label, Span\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom sklearn.datasets import load_wine\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\n\n# Theme tokens (Imprint palette — 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 categorical palette — canonical order, positions 1–4\nBRAND = \"#009E73\"  # pos 1: cumulative variance line (always first series)\nLAVENDER = \"#C475FD\"  # pos 2: individual variance bars\nBLUE = \"#4467A3\"  # pos 3: 90% threshold reference line\nOCHRE = \"#BD8233\"  # pos 4: 95% threshold reference line\n\n# Data — Wine dataset (13 chemical features, authentic PCA distribution)\nwine = load_wine()\nX_scaled = StandardScaler().fit_transform(wine.data)\npca = PCA()\npca.fit(X_scaled)\n\nn_components = np.arange(1, len(pca.explained_variance_ratio_) + 1)\ncumulative_variance = np.cumsum(pca.explained_variance_ratio_) * 100\nindividual_variance = pca.explained_variance_ratio_ * 100\n\nthreshold_90 = int(np.argmax(cumulative_variance >= 90) + 1)\nthreshold_95 = int(np.argmax(cumulative_variance >= 95) + 1)\n\n# ColumnDataSources\nsource_main = ColumnDataSource(\n    data={\n        \"component\": n_components,\n        \"cumulative\": cumulative_variance,\n        \"individual\": individual_variance,\n        \"base\": np.zeros_like(cumulative_variance),\n    }\n)\nsource_bars = ColumnDataSource(data={\"component\": n_components, \"individual\": individual_variance})\n\n# Title — scale fontsize if > 67 chars\ntitle_str = \"line-pca-variance-cumulative · python · bokeh · anyplot.ai\"\nn_chars = len(title_str)\nratio = 67 / n_chars if n_chars > 67 else 1.0\ntitle_fontsize = f\"{max(34, round(50 * ratio))}pt\"\n\n# Plot — canonical 3200×1800 bokeh canvas with toolbar disabled for PNG\np = figure(\n    width=3200,\n    height=1800,\n    title=title_str,\n    x_axis_label=\"Number of Principal Components\",\n    y_axis_label=\"Cumulative Explained Variance (%)\",\n    toolbar_location=None,\n    y_range=(-2, 112),\n    x_range=(0.3, 13.7),\n    min_border_bottom=160,\n    min_border_left=180,\n    min_border_top=110,\n    min_border_right=120,\n)\n\n# Area fill under cumulative curve (Bokeh Band — library-distinctive)\nband = Band(\n    base=\"component\",\n    upper=\"cumulative\",\n    lower=\"base\",\n    source=source_main,\n    fill_color=BRAND,\n    fill_alpha=0.08,\n    line_color=None,\n)\np.add_layout(band)\n\n# Individual variance bars (subtle background, secondary series)\np.vbar(\n    x=\"component\",\n    top=\"individual\",\n    source=source_bars,\n    width=0.5,\n    fill_color=LAVENDER,\n    fill_alpha=0.20,\n    line_color=LAVENDER,\n    line_alpha=0.30,\n    line_width=1.5,\n    legend_label=\"Individual Variance\",\n)\n\n# Cumulative variance line — capture renderer for HoverTool attachment\ncumulative_renderer = p.line(\n    x=\"component\",\n    y=\"cumulative\",\n    source=source_main,\n    line_width=6,\n    line_color=BRAND,\n    line_alpha=0.9,\n    legend_label=\"Cumulative Variance\",\n)\n\n# Markers at each component count\np.scatter(\n    x=\"component\",\n    y=\"cumulative\",\n    source=source_main,\n    size=18,\n    fill_color=BRAND,\n    line_color=PAGE_BG,\n    line_width=3,\n    fill_alpha=0.95,\n)\n\n# Horizontal threshold reference lines\np.add_layout(Span(location=90, dimension=\"width\", line_color=BLUE, line_width=2.5, line_dash=\"dashed\", line_alpha=0.7))\np.add_layout(Span(location=95, dimension=\"width\", line_color=OCHRE, line_width=2.5, line_dash=\"dashed\", line_alpha=0.7))\n\n# Right-edge threshold labels (kept inside canvas boundary)\np.add_layout(\n    Label(\n        x=13.2, y=86.0, text=\"90%\", text_font_size=\"30pt\", text_color=BLUE, text_align=\"right\", text_font_style=\"bold\"\n    )\n)\np.add_layout(\n    Label(\n        x=13.2, y=96.5, text=\"95%\", text_font_size=\"30pt\", text_color=OCHRE, text_align=\"right\", text_font_style=\"bold\"\n    )\n)\n\n# Glow-ring highlights at threshold crossings\nfor th, color in [(threshold_90, BLUE), (threshold_95, OCHRE)]:\n    p.scatter(\n        x=[th],\n        y=[cumulative_variance[th - 1]],\n        size=42,\n        fill_color=color,\n        fill_alpha=0.15,\n        line_color=color,\n        line_alpha=0.3,\n        line_width=2,\n    )\n    p.scatter(\n        x=[th],\n        y=[cumulative_variance[th - 1]],\n        size=28,\n        fill_color=color,\n        line_color=PAGE_BG,\n        line_width=3,\n        fill_alpha=0.9,\n    )\n\n# Crossing annotations — offset to avoid crowding\np.add_layout(\n    Label(\n        x=threshold_90 - 1.5,\n        y=cumulative_variance[threshold_90 - 1] - 9,\n        text=f\"{threshold_90} components ({cumulative_variance[threshold_90 - 1]:.1f}%)\",\n        text_font_size=\"24pt\",\n        text_color=BLUE,\n        text_font_style=\"bold\",\n        text_align=\"center\",\n    )\n)\np.add_layout(\n    Label(\n        x=threshold_95 + 1.5,\n        y=cumulative_variance[threshold_95 - 1] + 3,\n        text=f\"{threshold_95} components ({cumulative_variance[threshold_95 - 1]:.1f}%)\",\n        text_font_size=\"24pt\",\n        text_color=OCHRE,\n        text_font_style=\"bold\",\n        text_align=\"center\",\n    )\n)\n\n# HoverTool attached to named renderer (avoids fragile magic index)\np.add_tools(\n    HoverTool(\n        tooltips=[\n            (\"Component\", \"@component\"),\n            (\"Cumulative Variance\", \"@cumulative{0.1}%\"),\n            (\"Individual Variance\", \"@individual{0.1}%\"),\n        ],\n        mode=\"vline\",\n        renderers=[cumulative_renderer],\n    )\n)\n\n# Theme-adaptive chrome\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = INK_SOFT\n\np.title.text_font_size = title_fontsize\np.title.text_color = INK\np.title.align = \"center\"\np.title.text_font_style = \"bold\"\n\np.xaxis.axis_label_text_font_size = \"42pt\"\np.yaxis.axis_label_text_font_size = \"42pt\"\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_color = INK\np.xaxis.major_label_text_font_size = \"34pt\"\np.yaxis.major_label_text_font_size = \"34pt\"\np.xaxis.major_label_text_color = INK_SOFT\np.yaxis.major_label_text_color = INK_SOFT\np.xaxis.axis_line_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\np.xaxis.major_tick_line_color = INK_SOFT\np.yaxis.major_tick_line_color = INK_SOFT\np.xaxis.minor_tick_line_color = None\np.yaxis.minor_tick_line_color = None\n\np.xaxis.ticker = list(n_components)\n\np.ygrid.grid_line_color = INK\np.ygrid.grid_line_alpha = 0.15\np.xgrid.grid_line_color = INK\np.xgrid.grid_line_alpha = 0.08\n\np.legend.location = \"center_right\"\np.legend.label_text_font_size = \"34pt\"\np.legend.label_text_color = INK_SOFT\np.legend.background_fill_color = ELEVATED_BG\np.legend.border_line_color = INK_SOFT\np.legend.border_line_width = 1\np.legend.padding = 20\np.legend.margin = 30\np.legend.glyph_height = 40\np.legend.glyph_width = 40\np.legend.spacing = 16\n\n# Save interactive HTML (required catalog artifact)\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with headless Chrome — CDP override pins inner viewport to exact dims\n# (--window-size alone gives 1661 instead of 1800 due to browser chrome offset)\nW, H = 3200, 1800\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\ndriver = webdriver.Chrome(options=opts)\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n\n# Belt-and-braces: ensure saved PNG is exactly W×H so the post-render gate passes\nfrom PIL import Image as _PILImage\n\n\n_img = _PILImage.open(f\"plot-{THEME}.png\").convert(\"RGB\")\nif _img.size != (W, H):\n    _norm = _PILImage.new(\"RGB\", (W, H), PAGE_BG)\n    _norm.paste(_img, ((W - _img.size[0]) // 2, (H - _img.size[1]) // 2))\n    _norm.save(f\"plot-{THEME}.png\")\n"}