{"spec_id":"shap-waterfall","library":"letsplot","language":"python","code":"\"\"\" anyplot.ai\nshap-waterfall: SHAP Waterfall Plot for Feature Attribution\nLibrary: letsplot 4.11.0 | Python 3.14.10\nQuality: 78/100 | Updated: 2026-11-13\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom lets_plot import *\n\n\nLetsPlot.setup_html()\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\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\n# Imprint palette: red for positive SHAP (raises risk), blue for negative (lowers risk)\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nPOS_COLOR = IMPRINT_PALETTE[4]\nNEG_COLOR = IMPRINT_PALETTE[2]\n\n# Columns: set these to your table's column names\nFEATURE = \"Feature\"  # role: feature\nSHAP_VALUE = \"SHAP value (change in readmission probability)\"  # 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# One patient's 30-day hospital readmission risk, explained feature by feature\ndf = pd.DataFrame(\n    {\n        FEATURE: [\n            \"Prior Admissions (12 mo)\",\n            \"Home Care Arranged\",\n            \"Age\",\n            \"Comorbidity Count\",\n            \"Length of Stay\",\n            \"Medication Count\",\n            \"Discharge Weekday\",\n            \"Hemoglobin Level\",\n            \"Insurance Type\",\n            \"Emergency Admission\",\n            \"Distance to Hospital\",\n            \"Smoking Status\",\n        ],\n        SHAP_VALUE: [0.09, -0.07, 0.06, 0.05, -0.04, 0.04, -0.03, 0.03, -0.02, 0.02, -0.01, 0.01],\n        BASE_VALUE: 0.15,\n    }\n)\n\n# Plot: reads only df and the constants above\ntable = df.reindex(df[SHAP_VALUE].abs().sort_values(ascending=False, kind=\"stable\").index).reset_index(drop=True)\nn = len(table)\nbase_value = float(table[BASE_VALUE].iloc[0])\nfinal_value = base_value + float(table[SHAP_VALUE].sum())\n\n# Cumulative waterfall positions; the largest contributor sits at the top\nends = base_value + table[SHAP_VALUE].cumsum()\nstarts = ends - table[SHAP_VALUE]\nchain = np.concatenate([[base_value], ends.to_numpy()])\nspan = chain.max() - chain.min()\n\nhalf = 0.38\ntable[\"y\"] = np.arange(n, 0, -1)\ntable[\"ymin\"] = table[\"y\"] - half\ntable[\"ymax\"] = table[\"y\"] + half\ntable[\"xmin\"] = np.minimum(starts, ends)\ntable[\"xmax\"] = np.maximum(starts, ends)\ntable[\"direction\"] = np.where(table[SHAP_VALUE] >= 0, \"positive\", \"negative\")\ntable[\"label\"] = table[SHAP_VALUE].map(lambda v: f\"{v:+.2f}\")\ntable[\"text_x\"] = np.where(table[SHAP_VALUE] >= 0, table[\"xmax\"] + 0.02 * span, table[\"xmin\"] - 0.02 * span)\ndf_pos = table[table[SHAP_VALUE] >= 0]\ndf_neg = table[table[SHAP_VALUE] < 0]\n\n# Dotted connectors in the gap between consecutive bars\ndf_conn = pd.DataFrame(\n    {\"x\": ends.to_numpy()[:-1], \"y\": table[\"y\"].to_numpy()[:-1] - half, \"yend\": table[\"y\"].to_numpy()[1:] + half}\n)\n\n# Reference-line labels above the top bar\nlabel_y = n + 1.0\ndf_ref_base = pd.DataFrame({\"x\": [base_value - 0.02 * span], \"y\": [label_y], \"label\": [f\"Base = {base_value:.2f}\"]})\ndf_ref_pred = pd.DataFrame(\n    {\"x\": [final_value + 0.02 * span], \"y\": [label_y], \"label\": [f\"Predicted = {final_value:.2f}\"]}\n)\n\ntitle = \"Hospital Readmission Risk  ·  shap-waterfall  ·  python  ·  letsplot  ·  anyplot.ai\"\ntitle_size = round(16 * min(1.0, 67 / len(title)))\n\nanyplot_theme = theme(\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_line(color=INK_MUTED, size=0.15),\n    panel_grid_major_y=element_blank(),\n    panel_grid_minor=element_blank(),\n    axis_title=element_text(color=INK, size=12),\n    axis_text_y=element_text(color=INK_SOFT, size=11),\n    axis_text_x=element_text(color=INK_SOFT, size=10),\n    axis_line_x=element_line(color=INK_SOFT, size=0.5),\n    axis_line_y=element_blank(),\n    axis_ticks=element_blank(),\n    plot_title=element_text(color=INK, size=title_size),\n    legend_position=\"none\",\n)\n\nplot = (\n    ggplot()\n    + geom_vline(xintercept=base_value, color=INK_SOFT, size=0.5, linetype=\"dashed\")\n    + geom_rect(data=table, mapping=aes(xmin=\"xmin\", xmax=\"xmax\", ymin=\"ymin\", ymax=\"ymax\", fill=\"direction\"))\n    + geom_segment(\n        data=df_conn, mapping=aes(x=\"x\", xend=\"x\", y=\"y\", yend=\"yend\"), color=INK_SOFT, size=0.4, linetype=\"dotted\"\n    )\n    + geom_text(data=df_pos, mapping=aes(x=\"text_x\", y=\"y\", label=\"label\"), color=INK_SOFT, size=4.5, hjust=0)\n    + geom_text(data=df_neg, mapping=aes(x=\"text_x\", y=\"y\", label=\"label\"), color=INK_SOFT, size=4.5, hjust=1)\n    + geom_text(data=df_ref_base, mapping=aes(x=\"x\", y=\"y\", label=\"label\"), color=INK, size=5, hjust=1)\n    + geom_text(data=df_ref_pred, mapping=aes(x=\"x\", y=\"y\", label=\"label\"), color=INK, size=5, hjust=0)\n    + geom_vline(xintercept=final_value, color=INK, size=0.7)\n    + scale_fill_manual(values={\"positive\": POS_COLOR, \"negative\": NEG_COLOR})\n    + scale_x_continuous(limits=[chain.min() - 0.45 * span, chain.max() + 0.45 * span], expand=[0, 0])\n    + scale_y_continuous(breaks=table[\"y\"].tolist(), labels=table[FEATURE].tolist(), limits=[0.5, n + 1.5])\n    + labs(x=SHAP_VALUE, y=\"\", title=title)\n    + ggsize(800, 450)\n    + theme_minimal()\n    + anyplot_theme\n)\n\nggsave(plot, f\"plot-{THEME}.png\", scale=4, path=\".\")\nggsave(plot, f\"plot-{THEME}.html\", path=\".\")\n"}