{"spec_id":"ice-basic","library":"seaborn","language":"python","code":"\"\"\" anyplot.ai\nice-basic: Individual Conditional Expectation (ICE) Plot\nLibrary: seaborn 0.13.2 | Python 3.13.15\nQuality: 92/100 | Updated: 2026-08-17\n\"\"\"\n\nimport os\nimport sys\n\n\n# Prevent this file from shadowing the installed seaborn package\n_this_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if not (p and os.path.abspath(p) == _this_dir)]\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.colors import LinearSegmentedColormap, Normalize\nfrom sklearn.ensemble import GradientBoostingRegressor\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\"\nBRAND = \"#009E73\"  # Imprint palette position 1 — ICE lines (low end of gradient)\nPDP_COLOR = \"#C475FD\"  # Imprint palette position 2 — PDP overlay\nimprint_seq = LinearSegmentedColormap.from_list(\"imprint_seq\", [BRAND, \"#4467A3\"])\n\nsns.set_theme(\n    style=\"ticks\",\n    rc={\n        \"figure.facecolor\": PAGE_BG,\n        \"axes.facecolor\": PAGE_BG,\n        \"axes.edgecolor\": INK_SOFT,\n        \"axes.labelcolor\": INK,\n        \"text.color\": INK,\n        \"xtick.color\": INK_SOFT,\n        \"ytick.color\": INK_SOFT,\n        \"grid.color\": INK,\n        \"grid.alpha\": 0.12,\n        \"legend.facecolor\": ELEVATED_BG,\n        \"legend.edgecolor\": INK_SOFT,\n    },\n)\n\n# Data — synthetic housing dataset\nnp.random.seed(42)\nn_obs = 100\nsqft = np.random.uniform(800, 3500, n_obs)\nbedrooms = np.random.randint(2, 6, n_obs).astype(float)\nage = np.random.uniform(0, 50, n_obs)\ndistance = np.random.uniform(1, 25, n_obs)\n\nprice = 0.15 * sqft + 25.0 * bedrooms - 0.5 * age - 2.5 * distance + np.random.normal(0, 30, n_obs)\n\nX = np.column_stack([sqft, bedrooms, age, distance])\nmodel = GradientBoostingRegressor(n_estimators=150, max_depth=4, random_state=42)\nmodel.fit(X, price)\n\n# Compute ICE matrix — each row is one observation, each column a grid point\nn_grid = 60\nsqft_grid = np.linspace(800, 3500, n_grid)\nice_matrix = np.zeros((n_obs, n_grid))\nfor j, val in enumerate(sqft_grid):\n    X_tmp = X.copy()\n    X_tmp[:, 0] = val\n    ice_matrix[:, j] = model.predict(X_tmp)\n\npdp = ice_matrix.mean(axis=0)\n\n# Long-form DataFrame for seaborn\nobs_ids = np.repeat(np.arange(n_obs), n_grid)\nsqft_vals = np.tile(sqft_grid, n_obs)\nbedrooms_vals = np.repeat(bedrooms, n_grid)\ndf_ice = pd.DataFrame({\"obs_id\": obs_ids, \"sqft\": sqft_vals, \"price\": ice_matrix.ravel(), \"bedrooms\": bedrooms_vals})\n\n# Plot — 3200x1800 canvas (figsize x dpi), bbox_inches left at default (None)\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# ICE lines — one per observation via seaborn lineplot with units, color-coded by\n# bedrooms (a second feature) with an Imprint sequential colormap to surface\n# interaction effects hidden by the flat single-color band\nsns.lineplot(\n    data=df_ice,\n    x=\"sqft\",\n    y=\"price\",\n    units=\"obs_id\",\n    hue=\"bedrooms\",\n    estimator=None,\n    palette=imprint_seq,\n    linewidth=0.6,\n    alpha=0.35,\n    legend=False,\n    ax=ax,\n)\n\n# PDP overlay — bold average marginal effect, drawn via seaborn (not raw matplotlib)\nsns.lineplot(x=sqft_grid, y=pdp, color=PDP_COLOR, linewidth=3, ax=ax, zorder=5, label=\"Partial Dependence (PDP)\")\n\n# Rug plot — observed sqft distribution\nsns.rugplot(x=sqft, color=INK_SOFT, alpha=0.75, height=0.045, expand_margins=False, ax=ax)\n\n# Colorbar — decodes the bedrooms color gradient on the ICE lines\nbedrooms_norm = Normalize(vmin=bedrooms.min(), vmax=bedrooms.max())\nsm = plt.cm.ScalarMappable(cmap=imprint_seq, norm=bedrooms_norm)\nsm.set_array([])\ncbar = fig.colorbar(sm, ax=ax, pad=0.02, fraction=0.035)\ncbar.set_label(f\"Bedrooms (ICE curve color, n={n_obs})\", color=INK, fontsize=9)\ncbar.ax.tick_params(colors=INK_SOFT, labelsize=7)\ncbar.outline.set_edgecolor(INK_SOFT)\n\n# Annotation — calls out the piecewise/staircase PDP shape from the tree ensemble\njump_idx = int(np.argmax(np.abs(np.diff(pdp)))) + 1\nann_x, ann_y = sqft_grid[jump_idx], pdp[jump_idx]\ndx = -450 if ann_x > sqft_grid.mean() else 450\ndy = 55 if ann_y < pdp.mean() else -55\nax.annotate(\n    \"Piecewise jump —\\ntree-ensemble split\",\n    xy=(ann_x, ann_y),\n    xytext=(ann_x + dx, ann_y + dy),\n    fontsize=8,\n    color=INK,\n    ha=\"right\" if dx < 0 else \"left\",\n    arrowprops={\"arrowstyle\": \"->\", \"color\": INK_SOFT, \"lw\": 1.1},\n)\n\n# Style\nax.set_xlabel(\"Square Footage (sq ft)\", fontsize=10, color=INK)\nax.set_ylabel(\"Predicted House Price ($K)\", fontsize=10, color=INK)\nax.set_title(\"ice-basic · python · seaborn · anyplot.ai\", fontsize=12, fontweight=\"medium\", color=INK)\nax.tick_params(axis=\"both\", labelsize=8, colors=INK_SOFT, length=0)\nsns.despine(ax=ax)\nax.spines[\"left\"].set_color(INK_SOFT)\nax.spines[\"bottom\"].set_color(INK_SOFT)\nax.yaxis.grid(True, alpha=0.12, linewidth=0.8, color=INK)\n\nlegend = ax.legend(\n    loc=\"upper left\",\n    fontsize=8,\n    framealpha=0.92,\n    facecolor=ELEVATED_BG,\n    edgecolor=INK_SOFT,\n    fancybox=True,\n    borderpad=0.6,\n)\nlegend.get_frame().set_linewidth(0.6)\nfor text in legend.get_texts():\n    text.set_color(INK)\n\n# Save\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}