{"spec_id":"histogram-capability","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\nhistogram-capability: Process Capability Plot with Specification Limits\nLibrary: plotnine 0.15.7 | Python 3.13.14\nQuality: 88/100 | Updated: 2026-06-20\n\"\"\"\n\nimport os\nimport sys\n\n\n# Prevent this file from shadowing the plotnine library (same filename as the lib)\n_script_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if os.path.abspath(p or \".\") != _script_dir]\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    after_stat,\n    annotate,\n    coord_cartesian,\n    element_blank,\n    element_line,\n    element_rect,\n    element_text,\n    geom_histogram,\n    geom_rect,\n    geom_vline,\n    ggplot,\n    labs,\n    scale_x_continuous,\n    scale_y_continuous,\n    stat_function,\n    theme,\n    theme_minimal,\n)\nfrom scipy import stats\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 (theme-independent data colors)\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nBRAND = IMPRINT_PALETTE[0]  # #009E73 — first series: histogram bars\nBLUE = IMPRINT_PALETTE[2]  # #4467A3 — target line\nRED = IMPRINT_PALETTE[4]  # #AE3030 — LSL/USL limits (semantic error anchor)\n\n# Data — shaft diameter measurements (mm)\nnp.random.seed(42)\ntarget = 10.00\nlsl = 9.95\nusl = 10.05\n# Mean slightly above target to illustrate Cp vs Cpk difference\nmeasurements = np.random.normal(loc=10.008, scale=0.012, size=200)\n\n# Capability indices\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\ndf = pd.DataFrame({\"diameter\": measurements})\n\n# Fitted normal PDF\nnorm_pdf = lambda x: stats.norm.pdf(x, mean_val, sigma)\npeak_density = norm_pdf(mean_val)\n\n# Specification zone — ymax set very high so the top edge is clipped by the panel,\n# eliminating the abrupt visual boundary from the previous implementation\nspec_zone = pd.DataFrame({\"xmin\": [lsl], \"xmax\": [usl], \"ymin\": [0.0], \"ymax\": [peak_density * 3.0]})\n\n# Capability statistics box label\nstats_label = f\"Cp  = {cp:.2f}\\nCpk = {cpk:.2f}\\nμ    = {mean_val:.4f}\\nσ    = {sigma:.4f}\"\n\n# Title fontsize — scale linearly off 67-char baseline\ntitle = \"histogram-capability · python · plotnine · anyplot.ai\"\nn = len(title)\nratio = 67 / n if n > 67 else 1.0\ntitle_size = max(8, round(12 * ratio))\n\n# Plot\nplot = (\n    ggplot(df, aes(x=\"diameter\"))\n    # Spec zone shading (extends beyond visible y range to avoid abrupt upper edge)\n    + geom_rect(\n        aes(xmin=\"xmin\", xmax=\"xmax\", ymin=\"ymin\", ymax=\"ymax\"),\n        data=spec_zone,\n        fill=BRAND,\n        alpha=0.07,\n        inherit_aes=False,\n    )\n    # Histogram bars (density scale)\n    + geom_histogram(aes(y=after_stat(\"density\")), bins=25, fill=BRAND, color=PAGE_BG, alpha=0.8)\n    # Fitted normal distribution curve\n    + stat_function(fun=norm_pdf, color=INK, size=1.0, n=300)\n    # Specification limit lines\n    + geom_vline(xintercept=lsl, linetype=\"dashed\", color=RED, size=1.2)\n    + geom_vline(xintercept=usl, linetype=\"dashed\", color=RED, size=1.2)\n    # Target line\n    + geom_vline(xintercept=target, linetype=\"dashdot\", color=BLUE, size=1.0)\n    # Limit labels\n    + annotate(\"text\", x=lsl - 0.003, y=peak_density * 0.95, label=\"LSL\", size=4.0, color=RED, fontweight=\"bold\")\n    + annotate(\"text\", x=usl + 0.003, y=peak_density * 0.95, label=\"USL\", size=4.0, color=RED, fontweight=\"bold\")\n    + annotate(\n        \"label\",\n        x=target + 0.004,\n        y=peak_density * 0.82,\n        label=\"Target\",\n        size=4.2,\n        color=BLUE,\n        fontweight=\"bold\",\n        fill=ELEVATED_BG,\n        alpha=0.85,\n        label_size=0.3,\n        label_padding=0.4,\n    )\n    # Capability statistics box (theme-adaptive fill and text color)\n    + annotate(\n        \"label\",\n        x=mean_val + 3.5 * sigma,\n        y=peak_density * 0.70,\n        label=stats_label,\n        size=4.0,\n        color=INK,\n        ha=\"left\",\n        fill=ELEVATED_BG,\n        alpha=0.95,\n        label_padding=0.7,\n        label_size=0.4,\n    )\n    + labs(x=\"Shaft Diameter (mm)\", y=\"Density\", title=title)\n    + scale_x_continuous(breaks=np.round(np.arange(9.94, 10.07, 0.01), 2).tolist())\n    + scale_y_continuous(expand=(0, 0, 0, 0))\n    # Clip y-axis to data range; spec zone extends to ymax*3 so it fills the panel\n    # without a visible upper boundary edge\n    + coord_cartesian(ylim=(0, peak_density * 1.15))\n    + theme_minimal()\n    + theme(\n        figure_size=(8, 4.5),\n        text=element_text(size=7, color=INK),\n        axis_title=element_text(size=10, color=INK),\n        axis_text=element_text(size=8, color=INK_SOFT),\n        axis_title_x=element_text(margin={\"t\": 10}),\n        axis_title_y=element_text(margin={\"r\": 10}),\n        plot_title=element_text(size=title_size, color=INK),\n        legend_text=element_text(size=8, color=INK_SOFT),\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        panel_background=element_rect(fill=PAGE_BG),\n        panel_border=element_blank(),\n        panel_grid_major_x=element_blank(),\n        panel_grid_minor=element_blank(),\n        panel_grid_major_y=element_line(color=INK, size=0.3, alpha=0.15),\n        plot_margin=0.04,\n    )\n)\n\n# Save\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\", verbose=False)\n"}