{"spec_id":"histogram-capability","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nhistogram-capability: Process Capability Plot with Specification Limits\nLibrary: bokeh 3.9.1 | Python 3.13.14\nQuality: 89/100 | Updated: 2026-06-20\n\"\"\"\n\nimport os\nimport sys\n\n\n# Remove this file's own directory from sys.path so 'import bokeh' resolves\n# to the installed package, not this file.\n_here = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if os.path.abspath(p or \".\") != _here]\n\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, HoverTool, Label, Legend, LegendItem, Span\nfrom bokeh.plotting import figure\nfrom scipy import stats\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\n\n# Imprint palette — theme-adaptive chrome tokens\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\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\n# Imprint categorical palette (8 hues, hybrid-v3 sort order)\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nANYPLOT_AMBER = \"#DDCC77\"  # warning / caution anchor\n\n# Data — machined shaft diameter (mm)\n# Barely-capable process (Cp ~1.10, Cpk ~1.05) with sigma wide enough that\n# the distribution fills the spec window and tails approach both LSL and USL.\nnp.random.seed(42)\nlsl = 9.950\nusl = 10.050\ntarget = 10.000\nmeasurements = np.random.normal(loc=10.002, scale=0.0152, size=200)\n\n# Statistics\nmean_val = np.mean(measurements)\nsigma = np.std(measurements, ddof=1)\ncp = (usl - lsl) / (6 * sigma)\ncpk = min((usl - mean_val) / (3 * sigma), (mean_val - lsl) / (3 * sigma))\n\n# Histogram bins\ncounts, edges = np.histogram(measurements, bins=25)\nleft_edges = edges[:-1]\nright_edges = edges[1:]\nmax_count = counts.max()\n\nsource = ColumnDataSource(\n    data={\n        \"left\": left_edges,\n        \"right\": right_edges,\n        \"top\": counts,\n        \"bottom\": [0] * len(counts),\n        \"count\": counts,\n        \"bin_start\": [f\"{e:.4f}\" for e in left_edges],\n        \"bin_end\": [f\"{e:.4f}\" for e in right_edges],\n    }\n)\n\n# Normal distribution curve\nx_min = min(lsl - 2.0, measurements.min() - 0.5)\nx_max = max(usl + 2.0, measurements.max() + 0.5)\nx_curve = np.linspace(x_min, x_max, 300)\nbin_width = edges[1] - edges[0]\ny_curve = stats.norm.pdf(x_curve, mean_val, sigma) * len(measurements) * bin_width\ncurve_source = ColumnDataSource(data={\"x\": x_curve, \"y\": y_curve})\n\n# Create figure — canonical 3200×1800 landscape canvas\np = figure(\n    width=3200,\n    height=1800,\n    title=\"histogram-capability · python · bokeh · anyplot.ai\",\n    x_axis_label=\"Shaft Diameter (mm)\",\n    y_axis_label=\"Frequency\",\n    toolbar_location=None,\n    min_border_bottom=160,\n    min_border_left=180,\n    min_border_top=110,\n    min_border_right=50,\n)\n\n# Histogram bars — Imprint green (#009E73) is always first series\nbars = p.quad(\n    left=\"left\",\n    right=\"right\",\n    top=\"top\",\n    bottom=\"bottom\",\n    source=source,\n    fill_color=IMPRINT_PALETTE[0],\n    fill_alpha=0.75,\n    line_color=PAGE_BG,\n    line_width=1.5,\n    hover_fill_color=IMPRINT_PALETTE[3],  # ochre hover highlight\n    hover_fill_alpha=0.95,\n    hover_line_color=PAGE_BG,\n)\n\n# Hover tool\nhover = HoverTool(renderers=[bars], tooltips=[(\"Range\", \"@bin_start – @bin_end mm\"), (\"Count\", \"@count\")], mode=\"mouse\")\np.add_tools(hover)\n\n# Normal distribution curve — matching Imprint green\ncurve_line = p.line(x=\"x\", y=\"y\", source=curve_source, line_color=IMPRINT_PALETTE[0], line_width=4, line_alpha=0.9)\n\n# Spec limit lines — matte red (semantic: out-of-spec boundary)\nlsl_span = Span(\n    location=lsl, dimension=\"height\", line_color=IMPRINT_PALETTE[4], line_width=4, line_dash=[12, 6], line_alpha=0.9\n)\nusl_span = Span(\n    location=usl, dimension=\"height\", line_color=IMPRINT_PALETTE[4], line_width=4, line_dash=[12, 6], line_alpha=0.9\n)\np.add_layout(lsl_span)\np.add_layout(usl_span)\n\n# Target line — amber (semantic: nominal / reference)\ntarget_span = Span(\n    location=target, dimension=\"height\", line_color=ANYPLOT_AMBER, line_width=4, line_dash=[8, 4], line_alpha=0.9\n)\np.add_layout(target_span)\n\n# Mean line — theme-adaptive ink (structural / metadata layer)\nmean_span = Span(\n    location=mean_val, dimension=\"height\", line_color=INK_SOFT, line_width=3, line_dash=[6, 4], line_alpha=0.85\n)\np.add_layout(mean_span)\n\n# Off-screen renderers so Span objects appear in the legend\n_off = -9999\nlsl_legend_line = p.line(x=[_off, _off], y=[_off, _off], line_color=IMPRINT_PALETTE[4], line_width=4, line_dash=[12, 6])\nusl_legend_line = p.line(x=[_off, _off], y=[_off, _off], line_color=IMPRINT_PALETTE[4], line_width=4, line_dash=[12, 6])\ntarget_legend_line = p.line(x=[_off, _off], y=[_off, _off], line_color=ANYPLOT_AMBER, line_width=4, line_dash=[8, 4])\nmean_legend_line = p.line(x=[_off, _off], y=[_off, _off], line_color=INK_SOFT, line_width=3, line_dash=[6, 4])\n\n# Legend\nlegend = Legend(\n    items=[\n        LegendItem(label=\"Normal Fit\", renderers=[curve_line]),\n        LegendItem(label=f\"LSL = {lsl:.3f}\", renderers=[lsl_legend_line]),\n        LegendItem(label=f\"USL = {usl:.3f}\", renderers=[usl_legend_line]),\n        LegendItem(label=f\"Target = {target:.3f}\", renderers=[target_legend_line]),\n        LegendItem(label=f\"Mean = {mean_val:.4f}\", renderers=[mean_legend_line]),\n    ],\n    location=\"top_right\",\n    label_text_font_size=\"34pt\",\n    label_text_color=INK_SOFT,\n    glyph_width=60,\n    glyph_height=6,\n    spacing=14,\n    padding=20,\n    background_fill_alpha=0.92,\n    background_fill_color=ELEVATED_BG,\n    border_line_color=INK_SOFT,\n    border_line_alpha=0.5,\n)\np.add_layout(legend, \"center\")\n\n# Capability indices annotation\ncap_text = f\"Cp = {cp:.2f}  |  Cpk = {cpk:.2f}  |  N = {len(measurements)}\"\ncap_label = Label(\n    x=lsl + 0.001, y=max_count * 1.13, text=cap_text, text_font_size=\"30pt\", text_color=INK, text_font_style=\"bold\"\n)\np.add_layout(cap_label)\n\n# Typography — canonical bokeh sizes for 3200×1800\np.title.text_font_size = \"50pt\"\np.title.text_color = INK\np.title.text_font_style = \"bold\"\np.xaxis.axis_label_text_font_size = \"42pt\"\np.yaxis.axis_label_text_font_size = \"42pt\"\np.xaxis.axis_label_text_color = INK\np.xaxis.axis_label_text_font_style = \"normal\"\np.yaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_font_style = \"normal\"\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\n\n# Grid — y-axis only, subtle\np.xgrid.visible = False\np.ygrid.grid_line_alpha = 0.15\np.ygrid.grid_line_color = INK\np.ygrid.grid_line_width = 1\n\n# Chrome — theme-adaptive\np.outline_line_color = INK_SOFT\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.xaxis.axis_line_width = 2\np.yaxis.axis_line_width = 2\np.xaxis.axis_line_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\np.xaxis.minor_tick_line_color = None\np.yaxis.minor_tick_line_color = None\np.xaxis.major_tick_line_color = INK_SOFT\np.yaxis.major_tick_line_color = INK_SOFT\n\n# Axis ranges — tightened to avoid empty space at edges\ndata_min = measurements.min()\ndata_max = measurements.max()\nspec_min = min(lsl, data_min)\nspec_max = max(usl, data_max)\nedge_margin = (spec_max - spec_min) * 0.06\np.x_range.start = spec_min - edge_margin\np.x_range.end = spec_max + edge_margin\np.y_range.start = 0\np.y_range.end = max_count * 1.30\n\n# Save interactive HTML artifact\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot via headless Chrome — Selenium 4 auto-resolves chromedriver.\n# Use CDP captureScreenshot with captureBeyondViewport=True so the full\n# 3200×1800 Bokeh canvas is captured even when Chrome's inner viewport is\n# smaller than the outer window-size (headless Chrome reserves ~143px for\n# virtual browser chrome that shrinks innerHeight below the window height).\nimport base64\n\n\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.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)\nresult = driver.execute_cdp_cmd(\n    \"Page.captureScreenshot\",\n    {\"format\": \"png\", \"clip\": {\"x\": 0, \"y\": 0, \"width\": W, \"height\": H, \"scale\": 1}, \"captureBeyondViewport\": True},\n)\nwith open(f\"plot-{THEME}.png\", \"wb\") as f:\n    f.write(base64.b64decode(result[\"data\"]))\ndriver.quit()\n"}