{"spec_id":"ice-basic","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\nice-basic: Individual Conditional Expectation (ICE) Plot\nLibrary: plotnine 0.15.8 | Python 3.13.15\nQuality: 92/100 | Updated: 2026-08-17\n\"\"\"\n\nimport os\nimport sys\n\n\n# Prevent this script from shadowing the plotnine package\n_here = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if os.path.abspath(p if p else \".\") != _here]\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    annotate,\n    element_blank,\n    element_line,\n    element_rect,\n    element_text,\n    geom_line,\n    geom_rug,\n    geom_vline,\n    ggplot,\n    labs,\n    scale_x_continuous,\n    theme,\n)\nfrom sklearn.ensemble import GradientBoostingRegressor\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 — first series is always #009E73\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nBRAND = IMPRINT_PALETTE[0]\nPDP_COLOR = IMPRINT_PALETTE[1]\n\n# Data — synthetic housing dataset\nnp.random.seed(42)\nn_obs = 120\n\narea = np.random.uniform(600, 4000, n_obs)\nbedrooms = np.random.randint(1, 6, n_obs).astype(float)\nage_years = np.random.uniform(1, 50, n_obs)\nlocation = np.random.uniform(1, 10, n_obs)\n\nX = np.column_stack([area, bedrooms, age_years, location])\ny = area * 120 + bedrooms * 25000 - age_years * 800 + location * 40000 + np.random.normal(0, 25000, n_obs)\n\nmodel = GradientBoostingRegressor(n_estimators=150, max_depth=3, random_state=42)\nmodel.fit(X, y)\n\n# ICE curves: vary area across a grid, hold all other features at observed values\nn_grid = 60\narea_grid = np.linspace(area.min(), area.max(), n_grid)\n\nice_rows = []\nfor obs_id in range(n_obs):\n    X_grid = np.tile(X[obs_id], (n_grid, 1))\n    X_grid[:, 0] = area_grid\n    preds = model.predict(X_grid)\n    for feat_val, pred in zip(area_grid, preds, strict=False):\n        ice_rows.append({\"observation_id\": str(obs_id), \"feature_value\": feat_val, \"prediction\": pred / 1000})\n\nice_df = pd.DataFrame(ice_rows)\n\n# PDP: average prediction across all observations at each grid point\npdp_df = ice_df.groupby(\"feature_value\")[\"prediction\"].mean().reset_index()\n\n# Rug: observed area values\nrug_df = pd.DataFrame({\"feature_value\": area})\n\n# Annotation anchor: PDP value at ~75% of area range (past the step discontinuity)\nann_idx = int(n_grid * 0.75)\nann_x = float(area_grid[ann_idx])\nann_y = float(pdp_df.iloc[ann_idx][\"prediction\"]) + 25\n\n# Largest single-step jump in the PDP curve — marks the tree-split boundary the model learned\njump_idx = int(pdp_df[\"prediction\"].diff().abs().idxmax())\nsplit_x = float(pdp_df.loc[jump_idx, \"feature_value\"])\nsplit_label_y = float(pdp_df[\"prediction\"].max()) + 20\n\n# Plot\nanyplot_theme = theme(\n    figure_size=(8, 4.5),\n    plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n    panel_background=element_rect(fill=PAGE_BG),\n    panel_grid_major_y=element_line(color=INK, size=0.3, alpha=0.12),\n    panel_grid_major_x=element_blank(),\n    panel_grid_minor=element_blank(),\n    panel_border=element_blank(),\n    axis_title=element_text(color=INK, size=10),\n    axis_text=element_text(color=INK_SOFT, size=8),\n    axis_line=element_line(color=INK_SOFT),\n    plot_title=element_text(color=INK, size=12, face=\"bold\"),\n    legend_position=\"none\",\n    plot_margin=0.05,\n)\n\nplot = (\n    ggplot(ice_df, aes(x=\"feature_value\", y=\"prediction\", group=\"observation_id\"))\n    + geom_line(alpha=0.12, color=BRAND, size=0.5)\n    + geom_vline(xintercept=split_x, color=INK_SOFT, alpha=0.5, linetype=\"dashed\", size=0.4)\n    + geom_line(\n        data=pdp_df, mapping=aes(x=\"feature_value\", y=\"prediction\"), color=PDP_COLOR, size=2.5, inherit_aes=False\n    )\n    + geom_rug(data=rug_df, mapping=aes(x=\"feature_value\"), color=INK_SOFT, alpha=0.4, sides=\"b\", inherit_aes=False)\n    + annotate(\"text\", x=ann_x, y=ann_y, label=\"PDP (avg effect)\", color=PDP_COLOR, size=4.0, fontweight=\"bold\")\n    + annotate(\n        \"text\",\n        x=split_x,\n        y=split_label_y,\n        label=f\"model split ~{split_x:.0f} sq ft\",\n        color=INK_SOFT,\n        size=3.2,\n        fontstyle=\"italic\",\n        ha=\"center\",\n    )\n    + scale_x_continuous(breaks=[1000, 1500, 2000, 2500, 3000, 3500])\n    + labs(x=\"House Area (sq ft)\", y=\"Predicted Price ($000s)\", title=\"ice-basic · plotnine · anyplot.ai\")\n    + anyplot_theme\n)\n\n# Save\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\")\n"}