{"spec_id":"shap-waterfall","library":"pygal","language":"python","code":"\"\"\" anyplot.ai\nshap-waterfall: SHAP Waterfall Plot for Feature Attribution\nLibrary: pygal 3.1.3 | Python 3.14.10\nQuality: 89/100 | Updated: 2026-11-08\n\"\"\"\n\nimport os\nimport sys\n\n\n# Prevent this file (pygal.py) from shadowing the installed pygal package\n_here = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if os.path.abspath(p or os.getcwd()) != _here]\n\nimport numpy as np\nimport pygal\nfrom pygal.style import Style\n\n\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\"\nRULE = \"rgba(26,26,23,0.15)\" if THEME == \"light\" else \"rgba(240,239,232,0.15)\"\n\n# Imprint semantic anchors: matte red pushes the prediction up, blue pushes it down\nPOSITIVE = \"#AE3030\"\nNEGATIVE = \"#4467A3\"\n\n# Data – customer churn prediction SHAP explanation\nfeature_names = [\n    \"Monthly Charges\",\n    \"Contract Type\",\n    \"Tenure\",\n    \"Online Security\",\n    \"Internet Service\",\n    \"Tech Support\",\n    \"Num. of Services\",\n    \"Payment Method\",\n    \"Device Protection\",\n    \"Streaming TV\",\n]\nshap_raw = [0.20, 0.15, -0.12, -0.10, 0.08, -0.06, 0.05, 0.04, -0.03, 0.02]\nbase_value = 0.25\nfinal_value = round(base_value + sum(shap_raw), 4)  # 0.48\n\n# Sort ascending by abs magnitude (pygal draws the first label at the bottom, the last at the top),\n# so the chain climbs from the base value at the bottom to the prediction next to the largest bar on top\nidx = sorted(range(len(shap_raw)), key=lambda i: abs(shap_raw[i]))\nfeatures = [feature_names[i] for i in idx]\nshap_vals = [shap_raw[i] for i in idx]\n\n# Cumulative chain from the base value to the prediction\nchain = base_value + np.concatenate([[0.0], np.cumsum(shap_vals)])\nleft_edges = np.minimum(chain[:-1], chain[1:])\n\n# Value axis: covers the chain only, with room right of the top bar for its value label\nstep = 10 ** np.floor(np.log10(chain.max() - chain.min()))\naxis_lo = np.floor(chain.min() / step) * step\naxis_hi = np.ceil((chain.max() + 0.25 * step) / (step / 2)) * (step / 2)\nticks = [t for t in np.arange(axis_lo, axis_hi + 1e-9, step) if min(abs(t - base_value), abs(t - final_value)) > 0.3 * step]\nreferences = [\n    {\"value\": base_value, \"label\": f\"Base {base_value:.2f}\"},\n    {\"value\": final_value, \"label\": f\"Prediction {final_value:.2f}\"},\n]\n\n# Waterfall stacking: a transparent spacer up to each segment's left edge, then the segment itself\nspacer_data = [{\"value\": float(edge), \"style\": \"fill: none; stroke: none\"} for edge in left_edges]\nshap_data = [\n    {\"value\": abs(v), \"color\": POSITIVE if v >= 0 else NEGATIVE, \"label\": f\"{v:+.2f}\"} for v in shap_vals\n]\n\n# Style\ncustom_style = Style(\n    background=PAGE_BG,\n    plot_background=PAGE_BG,\n    foreground=INK,\n    foreground_strong=INK,\n    foreground_subtle=INK_SOFT,\n    colors=(PAGE_BG, POSITIVE),\n    value_colors=(INK, INK),\n    opacity=1,\n    opacity_hover=0.85,\n    guide_stroke_color=RULE,\n    guide_stroke_dasharray=\"none\",\n    major_guide_stroke_color=INK,\n    major_guide_stroke_dasharray=\"18,10\",\n    title_font_size=56,\n    label_font_size=44,\n    major_label_font_size=44,\n    legend_font_size=44,\n    value_font_size=40,\n    value_label_font_size=40,\n    tooltip_font_size=36,\n    stroke_width=0,\n)\n\n# HorizontalStackedBar enables waterfall stacking via spacer + visible series\nchart = pygal.HorizontalStackedBar(\n    width=3200,\n    height=1800,\n    style=custom_style,\n    title=\"Customer Churn Prediction · shap-waterfall · python · pygal · anyplot.ai\",\n    x_title=\"Predicted churn probability (base value + SHAP contributions)\",\n    y_title=\"Feature (ordered by |SHAP value|)\",\n    show_legend=False,\n    show_y_guides=False,\n    show_x_guides=False,\n    range=(float(axis_lo), float(axis_hi)),\n    print_labels=True,\n    print_values=False,\n    print_values_position=\"top\",\n    truncate_label=-1,\n    margin=40,\n    spacing=30,\n    css=(\n        \"file://style.css\",\n        \"file://graph.css\",\n        # Segment values sit just right of each segment; the reference guides are drawn heavier than the grid;\n        # title_font_size sizes the axis titles, the plot title is set larger and bold here\n        \"inline:.text-overlay text.label { text-anchor: start; }\",\n        \"inline:.axis .major.guide.line { stroke-width: 4px; } .axis text.major { font-weight: bold; }\",\n        \"inline:.plot_title { font-size: 62px !important; font-weight: bold; }\",\n    ),\n)\n\nchart.x_labels = features\n# Value-axis ticks plus the base value and the prediction as labelled reference guides\nchart.y_labels = [{\"value\": float(t), \"label\": f\"{t:.1f}\"} for t in ticks] + references\nchart.y_labels_major = [r[\"value\"] for r in references]\n\nchart.add(\"\", spacer_data)\nchart.add(\"SHAP contribution\", shap_data)\n\n# Save\nchart.render_to_png(f\"plot-{THEME}.png\")\nwith open(f\"plot-{THEME}.html\", \"wb\") as f:\n    f.write(chart.render())\n"}