{"spec_id":"shap-waterfall","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nshap-waterfall: SHAP Waterfall Plot for Feature Attribution\nLibrary: bokeh 3.10.2 | Python 3.14.10\nQuality: 85/100 | Updated: 2026-11-13\n\"\"\"\n\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\n\n# Prevent this file from shadowing the bokeh package\n_this_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if os.path.abspath(p) != _this_dir and p != \"\"]\n\nimport pandas as pd\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, Range1d, Span\nfrom bokeh.plotting import figure\nfrom bokeh.resources import INLINE\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\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\n\n# Imprint palette, canonical order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nPOS_COLOR = IMPRINT_PALETTE[4]  # red — positive SHAP (pushes prediction up)\nNEG_COLOR = IMPRINT_PALETTE[2]  # blue — negative SHAP (pushes prediction down)\nLABEL_INK = \"#F0EFE8\"  # near-white for text on colored bar segments\n\n# Columns: set these to your table's column names\nFEATURE = \"Feature\"  # role: feature\nSHAP_VALUE = \"SHAP value\"  # role: shap_value\nBASE_VALUE = \"Base value\"  # role: base_value\n\n# Data: replace this block with your own table, for example df = pd.read_csv(\"shap.csv\")\n# Credit default risk model: explaining one loan applicant's prediction\ndf = pd.DataFrame(\n    {\n        FEATURE: [\n            \"Credit Score (715)\",\n            \"Debt-to-Income Ratio\",\n            \"Monthly Income\",\n            \"Late Payments (2)\",\n            \"Employment Duration\",\n            \"Loan Amount\",\n            \"Savings Balance\",\n            \"Credit History Age\",\n            \"Credit Inquiries (3)\",\n            \"Credit Cards Count\",\n            \"Housing (Renter)\",\n            \"Education Level\",\n        ],\n        SHAP_VALUE: [-0.18, 0.15, -0.12, 0.11, -0.08, 0.07, -0.05, -0.04, 0.04, 0.03, 0.02, -0.02],\n        BASE_VALUE: [0.35] * 12,\n    }\n)\n\n# Plot: reads only df and the constants above\n# Features sorted by |SHAP| so the largest contribution sits at the top\ndf = df.reindex(df[SHAP_VALUE].abs().sort_values(ascending=False, kind=\"stable\").index).reset_index(drop=True)\nbase_value = df[BASE_VALUE].iloc[0]\nends = base_value + df[SHAP_VALUE].cumsum()\nstarts = ends.shift(fill_value=base_value)\nfinal_value = ends.iloc[-1]\n\ndf[\"left\"] = pd.concat([starts, ends], axis=1).min(axis=1)\ndf[\"right\"] = pd.concat([starts, ends], axis=1).max(axis=1)\ndf[\"mid\"] = (df[\"left\"] + df[\"right\"]) / 2\ndf[\"end\"] = ends\ndf[\"color\"] = [POS_COLOR if v > 0 else NEG_COLOR for v in df[SHAP_VALUE]]\ndf[\"label\"] = [f\"{v:+.2f}\" for v in df[SHAP_VALUE]]\nsource = ColumnDataSource(df)\n\nfeatures = list(df[FEATURE])\nspan = df[\"right\"].max() - df[\"left\"].min()\nx_low = df[\"left\"].min() - 0.06 * span\nx_high = df[\"right\"].max() + 0.30 * span  # room for the base value label right of its line\n\np = figure(\n    width=3200,\n    height=1800,\n    # Reversed: bokeh puts the first factor at the bottom\n    y_range=list(reversed(features)),\n    x_range=Range1d(x_low, x_high),\n    title=\"Credit Default Risk · shap-waterfall · python · bokeh · anyplot.ai\",\n    toolbar_location=None,\n    x_axis_label=\"Cumulative Default Probability\",\n    min_border_bottom=150,\n    min_border_left=40,\n    min_border_top=110,\n    min_border_right=60,\n)\np.y_range.range_padding = 0.25  # headroom above the first bar for the reference labels\n\n# Waterfall bars\np.hbar(y=FEATURE, left=\"left\", right=\"right\", height=0.62, color=\"color\", alpha=0.9, source=source)\n\n# Connector lines: vertical dashed segments from each bar end to the next bar\np.segment(\n    x0=\"end\",\n    y0=FEATURE,\n    x1=\"end\",\n    y1=\"next_feature\",\n    line_color=INK_SOFT,\n    line_dash=\"dashed\",\n    line_width=2,\n    line_alpha=0.7,\n    source=ColumnDataSource(df.iloc[:-1].assign(next_feature=features[1:])),\n)\n\n# SHAP value labels centered on the bars\np.text(\n    x=\"mid\",\n    y=FEATURE,\n    text=\"label\",\n    text_align=\"center\",\n    text_baseline=\"middle\",\n    text_font_size=\"28pt\",\n    text_color=LABEL_INK,\n    text_font_style=\"bold\",\n    source=source,\n)\n\n# Reference lines for base value and final prediction\np.add_layout(\n    Span(location=base_value, dimension=\"height\", line_color=INK_SOFT, line_dash=\"dashed\", line_width=4, line_alpha=0.8)\n)\np.add_layout(Span(location=final_value, dimension=\"height\", line_color=INK, line_dash=\"solid\", line_width=4))\n\n# Reference labels in the empty headroom above the first bar: base to the right of its line,\n# final prediction to the left of its line (bokeh y_offset: negative moves up)\np.text(\n    x=[base_value],\n    y=[features[0]],\n    text=[f\"Base value: {base_value:.2f}\"],\n    x_offset=12,\n    y_offset=-70,\n    text_align=\"left\",\n    text_font_size=\"28pt\",\n    text_color=INK_SOFT,\n)\np.text(\n    x=[final_value],\n    y=[features[0]],\n    text=[f\"Prediction: {final_value:.2f}\"],\n    x_offset=-12,\n    y_offset=-70,\n    text_align=\"right\",\n    text_font_size=\"28pt\",\n    text_color=INK,\n    text_font_style=\"bold\",\n)\n\n# Theme-adaptive chrome\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = None\n\np.title.text_font_size = \"50pt\"\np.title.text_color = INK\np.title.text_font_style = \"bold\"\n\np.xaxis.axis_label_text_font_size = \"42pt\"\np.xaxis.axis_label_text_color = INK\np.xaxis.major_label_text_font_size = \"34pt\"\np.xaxis.major_label_text_color = INK_SOFT\np.xaxis.axis_line_color = INK_SOFT\np.xaxis.major_tick_line_color = INK_SOFT\np.xaxis.minor_tick_line_color = None\n\np.yaxis.major_label_text_font_size = \"30pt\"\np.yaxis.major_label_text_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\np.yaxis.major_tick_line_color = None\n\np.xgrid.grid_line_color = INK\np.xgrid.grid_line_alpha = 0.10\np.ygrid.grid_line_color = None\n\n# Save HTML and take PNG screenshot with headless Chrome\noutput_file(f\"plot-{THEME}.html\")\nsave(p, resources=INLINE)\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)\n\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ntime.sleep(4)\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}