{"spec_id":"box-notched","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nbox-notched: Notched Box Plot\nLibrary: bokeh 3.9.2 | Python 3.13.15\nQuality: 96/100 | Updated: 2026-08-18\n\"\"\"\n\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\n\n# Remove the script's own directory from sys.path so \"bokeh\" resolves to the\n# installed package, not this file.\n_this_dir = str(Path(__file__).parent.resolve())\nsys.path = [p for p in sys.path if os.path.abspath(p) != _this_dir and p != \"\"]\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, HoverTool\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\n# Theme tokens\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 (first series is always #009E73)\nIMPRINT = [\n    \"#009E73\",  # brand green\n    \"#C475FD\",  # lavender\n    \"#4467A3\",  # blue\n    \"#BD8233\",  # ochre\n    \"#AE3030\",  # matte red\n]\n\n# Data - Employee performance scores across departments\nnp.random.seed(42)\n\nraw_data = {\n    \"Engineering\": np.random.normal(78, 8, 60),\n    \"Sales\": np.random.normal(72, 12, 55),\n    \"Marketing\": np.random.normal(75, 6, 50),\n    \"Operations\": np.random.normal(68, 10, 65),\n    \"HR\": np.random.normal(74, 7, 45),\n}\n\n# Add some outliers (constrained to 0-100 range)\nraw_data[\"Sales\"] = np.append(raw_data[\"Sales\"], [45, 98])\nraw_data[\"Operations\"] = np.append(raw_data[\"Operations\"], [42, 95])\nraw_data[\"HR\"] = np.append(raw_data[\"HR\"], [50])\n\n# Clip all values to 0-100 range\nfor cat in raw_data:\n    raw_data[cat] = np.clip(raw_data[cat], 0, 100)\n\n# Compute box plot statistics with notches for each department, then rank by\n# median descending — turns the plot into a leaderboard-style comparison\n# instead of an arbitrary department order.\nstats = []\nfor cat, values in raw_data.items():\n    q1 = np.percentile(values, 25)\n    q2 = np.percentile(values, 50)\n    q3 = np.percentile(values, 75)\n    mean = values.mean()\n    iqr = q3 - q1\n    n = len(values)\n\n    lower_fence = q1 - 1.5 * iqr\n    upper_fence = q3 + 1.5 * iqr\n    in_range = values[(values >= lower_fence) & (values <= upper_fence)]\n    lower_whisker = in_range.min() if len(in_range) > 0 else q1\n    upper_whisker = in_range.max() if len(in_range) > 0 else q3\n\n    # Notch: 95% CI around median = ±1.57 × IQR / √n\n    notch_width = 1.57 * iqr / np.sqrt(n)\n\n    outliers = values[(values < lower_fence) | (values > upper_fence)]\n\n    stats.append(\n        {\n            \"category\": cat,\n            \"q1\": q1,\n            \"q2\": q2,\n            \"q3\": q3,\n            \"mean\": mean,\n            \"upper\": upper_whisker,\n            \"lower\": lower_whisker,\n            \"notch_lower\": q2 - notch_width,\n            \"notch_upper\": q2 + notch_width,\n            \"n\": n,\n            \"outliers\": outliers,\n        }\n    )\n\nstats.sort(key=lambda s: s[\"q2\"], reverse=True)\nfor i, s in enumerate(stats):\n    s[\"color\"] = IMPRINT[i]\n    s[\"label\"] = f\"{s['category']} (n={s['n']})\"\n\ncategories = [s[\"label\"] for s in stats]\n\n# Variable box width, proportional to sqrt(sample size) — the classic\n# varwidth-boxplot convention, so a wider box visually signals a more\n# trustworthy notch, not just decoration.\nn_values = [s[\"n\"] for s in stats]\nn_min, n_max = min(n_values), max(n_values)\n\n\ndef _width_for_n(n):\n    if n_max == n_min:\n        return 0.55\n    t = (n - n_min) / (n_max - n_min)\n    return 0.42 + t * (0.68 - 0.42)\n\n\n# Create figure\np = figure(\n    width=3200,\n    height=1800,\n    title=\"box-notched · python · bokeh · anyplot.ai\",\n    x_range=categories,\n    y_range=(0, 105),\n    y_axis_label=\"Performance Score (0–100)\",\n    x_axis_label=\"Department (ranked by median, n = sample size)\",\n    toolbar_location=None,\n    min_border_bottom=170,\n    min_border_left=190,\n    min_border_top=120,\n    min_border_right=60,\n)\n\n# Styling — canonical sizes for the 3200x1800 canvas\np.title.text_font_size = \"50pt\"\np.title.text_font_style = \"bold\"\np.xaxis.axis_label_text_font_size = \"42pt\"\np.yaxis.axis_label_text_font_size = \"42pt\"\np.xaxis.major_label_text_font_size = \"30pt\"\np.yaxis.major_label_text_font_size = \"34pt\"\n\n# Theme-adaptive chrome\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\n# No full-rectangle outline — the bottom/left axis lines already form the\n# L-shaped frame convention; a plot-wide outline would add top/right edges.\np.outline_line_color = None\n\np.title.text_color = INK\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_color = INK\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\n\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = INK\np.ygrid.grid_line_alpha = 0.15\n\n# Draw each notched box manually, with width scaled to sample size and a\n# hollow mean-diamond next to the median notch — the divergence between the\n# two is itself a signal of skew, giving the reader a second story beyond\n# \"which department is on top\".\nfor i, s in enumerate(stats):\n    q1, q2, q3 = s[\"q1\"], s[\"q2\"], s[\"q3\"]\n    nl, nu = s[\"notch_lower\"], s[\"notch_upper\"]\n    lower, upper = s[\"lower\"], s[\"upper\"]\n    color = s[\"color\"]\n\n    box_width = _width_for_n(s[\"n\"])\n    half_width = box_width / 2\n    notch_indent = box_width / 4\n    cap_width = box_width / 3\n\n    # Lower box (q1 to notch_lower)\n    p.quad(\n        top=[nl],\n        bottom=[q1],\n        left=[i - half_width],\n        right=[i + half_width],\n        fill_color=color,\n        fill_alpha=0.88,\n        line_color=INK_SOFT,\n        line_width=2,\n    )\n\n    # Upper box (notch_upper to q3)\n    p.quad(\n        top=[q3],\n        bottom=[nu],\n        left=[i - half_width],\n        right=[i + half_width],\n        fill_color=color,\n        fill_alpha=0.88,\n        line_color=INK_SOFT,\n        line_width=2,\n    )\n\n    # Left notch triangle\n    p.patch(\n        x=[i - half_width, i - notch_indent, i - half_width],\n        y=[nl, q2, nu],\n        fill_color=color,\n        fill_alpha=0.88,\n        line_color=INK_SOFT,\n        line_width=2,\n    )\n\n    # Right notch triangle\n    p.patch(\n        x=[i + half_width, i + notch_indent, i + half_width],\n        y=[nl, q2, nu],\n        fill_color=color,\n        fill_alpha=0.88,\n        line_color=INK_SOFT,\n        line_width=2,\n    )\n\n    # Median line (legend groups repeated labels into a single entry)\n    p.segment(\n        x0=[i - notch_indent],\n        x1=[i + notch_indent],\n        y0=[q2],\n        y1=[q2],\n        line_color=INK,\n        line_width=4,\n        legend_label=\"Median\",\n    )\n\n    # Mean marker — hollow diamond, offset just past the notch\n    p.scatter(\n        x=[i + notch_indent + 0.06],\n        y=[s[\"mean\"]],\n        marker=\"diamond\",\n        size=20,\n        fill_color=PAGE_BG,\n        line_color=INK,\n        line_width=2.5,\n        legend_label=\"Mean\",\n    )\n\n    # Whiskers (vertical lines)\n    p.segment(x0=[i], x1=[i], y0=[q3], y1=[upper], line_color=INK_SOFT, line_width=2)\n    p.segment(x0=[i], x1=[i], y0=[q1], y1=[lower], line_color=INK_SOFT, line_width=2)\n\n    # Whisker caps (horizontal lines)\n    p.segment(x0=[i - cap_width], x1=[i + cap_width], y0=[upper], y1=[upper], line_color=INK_SOFT, line_width=2)\n    p.segment(x0=[i - cap_width], x1=[i + cap_width], y0=[lower], y1=[lower], line_color=INK_SOFT, line_width=2)\n\n# Invisible hover-target quads (whisker-to-whisker) so the HTML export lets\n# readers inspect the exact q1/median/q3/mean/n behind each box on hover.\nhover_source = ColumnDataSource(\n    data={\n        \"left\": [i - _width_for_n(s[\"n\"]) / 2 for i, s in enumerate(stats)],\n        \"right\": [i + _width_for_n(s[\"n\"]) / 2 for i, s in enumerate(stats)],\n        \"top\": [s[\"upper\"] for s in stats],\n        \"bottom\": [s[\"lower\"] for s in stats],\n        \"category\": [s[\"category\"] for s in stats],\n        \"q1\": [s[\"q1\"] for s in stats],\n        \"median\": [s[\"q2\"] for s in stats],\n        \"q3\": [s[\"q3\"] for s in stats],\n        \"mean\": [s[\"mean\"] for s in stats],\n        \"n\": [s[\"n\"] for s in stats],\n    }\n)\nhover_glyph = p.quad(\n    top=\"top\", bottom=\"bottom\", left=\"left\", right=\"right\", source=hover_source, fill_alpha=0, line_alpha=0\n)\np.add_tools(\n    HoverTool(\n        renderers=[hover_glyph],\n        tooltips=[\n            (\"Department\", \"@category\"),\n            (\"n\", \"@n\"),\n            (\"Q1\", \"@q1{0.1f}\"),\n            (\"Median\", \"@median{0.1f}\"),\n            (\"Q3\", \"@q3{0.1f}\"),\n            (\"Mean\", \"@mean{0.1f}\"),\n        ],\n    )\n)\n\n# Draw outliers\noutlier_x, outlier_y, outlier_color = [], [], []\nfor s in stats:\n    for o in s[\"outliers\"]:\n        outlier_x.append(s[\"label\"])\n        outlier_y.append(o)\n        outlier_color.append(s[\"color\"])\n\nif outlier_x:\n    outlier_source = ColumnDataSource(data={\"x\": outlier_x, \"y\": outlier_y, \"color\": outlier_color})\n    p.scatter(\n        x=\"x\",\n        y=\"y\",\n        source=outlier_source,\n        marker=\"circle\",\n        size=16,\n        fill_color=PAGE_BG,\n        line_color=\"color\",\n        line_width=3,\n        fill_alpha=0.9,\n    )\n\n# Legend — explains the median-notch vs. mean-diamond encoding\np.legend.location = \"top_right\"\np.legend.orientation = \"horizontal\"\np.legend.background_fill_color = ELEVATED_BG\np.legend.border_line_color = INK_SOFT\np.legend.label_text_color = INK_SOFT\np.legend.label_text_font_size = \"28pt\"\np.legend.glyph_width = 40\np.legend.glyph_height = 40\np.legend.spacing = 30\np.legend.padding = 16\np.legend.margin = 20\n\n# Save HTML\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with headless Chrome\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)\n\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\n# Pin the exact viewport via CDP — headless Chrome's --window-size sets the\n# OUTER window and still reserves a phantom title-bar height, which would\n# otherwise shrink the screenshot below H.\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ntime.sleep(3)\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}