{"spec_id":"silhouette-basic","library":"seaborn","language":"python","code":"\"\"\" anyplot.ai\nsilhouette-basic: Silhouette Plot\nLibrary: seaborn 0.13.2 | Python 3.13.13\nQuality: 90/100 | Updated: 2026-05-10\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_samples, silhouette_score\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\"\n\n# Okabe-Ito palette (first series always #009E73)\nIMPRINT = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\"]\n\n# Set seaborn theme\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.10,\n        \"legend.facecolor\": ELEVATED_BG,\n        \"legend.edgecolor\": INK_SOFT,\n    },\n)\n\n# Customer segmentation synthetic data\nnp.random.seed(42)\nn_customers = 200\n\n# Generate customer features: spending, frequency, recency metrics\nspending = np.concatenate(\n    [\n        np.random.normal(1500, 300, 60),  # High spenders\n        np.random.normal(800, 200, 90),  # Medium spenders\n        np.random.normal(200, 100, 50),  # Low spenders\n    ]\n)\nfrequency = np.concatenate([np.random.normal(24, 5, 60), np.random.normal(12, 4, 90), np.random.normal(3, 2, 50)])\nrecency = np.concatenate([np.random.normal(5, 10, 60), np.random.normal(20, 15, 90), np.random.normal(60, 30, 50)])\n\nX = np.column_stack([spending, frequency, recency])\n\n# K-means clustering\nn_clusters = 3\nkmeans = KMeans(n_clusters=n_clusters, random_state=123, n_init=10)\ncluster_labels = kmeans.fit_predict(X)\n\n# Silhouette analysis\nsilhouette_vals = silhouette_samples(X, cluster_labels)\navg_score = silhouette_score(X, cluster_labels)\n\n# Create figure\nfig, ax = plt.subplots(figsize=(16, 9), facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\ny_lower = 10\ncluster_info = []\n\nfor i in range(n_clusters):\n    cluster_silhouette_vals = silhouette_vals[cluster_labels == i]\n    cluster_silhouette_vals.sort()\n\n    cluster_size = len(cluster_silhouette_vals)\n    y_upper = y_lower + cluster_size\n\n    y_positions = np.arange(y_lower, y_upper)\n\n    ax.barh(\n        y_positions,\n        cluster_silhouette_vals,\n        height=1.0,\n        color=IMPRINT[i],\n        edgecolor=IMPRINT[i],\n        alpha=0.85,\n        label=f\"Cluster {i}\",\n    )\n\n    cluster_avg = np.mean(cluster_silhouette_vals)\n    cluster_info.append((i, cluster_avg, (y_lower + y_upper) / 2))\n\n    y_lower = y_upper + 10\n\n# Average silhouette line\nax.axvline(x=avg_score, color=INK_SOFT, linestyle=\"--\", linewidth=2.5, label=f\"Average: {avg_score:.3f}\")\n\n# Cluster average annotations\nfor cluster_id, cluster_avg, y_center in cluster_info:\n    ax.text(\n        -0.08,\n        y_center,\n        f\"C{cluster_id}\\n{cluster_avg:.2f}\",\n        fontsize=14,\n        fontweight=\"medium\",\n        color=IMPRINT[cluster_id],\n        va=\"center\",\n        ha=\"right\",\n    )\n\n# Style\nax.set_xlim([-0.15, 1.0])\nax.set_xlabel(\"Silhouette Coefficient\", fontsize=20, color=INK)\nax.set_ylabel(\"Samples (grouped by cluster)\", fontsize=20, color=INK)\nax.set_title(\"silhouette-basic · seaborn · anyplot.ai\", fontsize=24, fontweight=\"medium\", color=INK)\nax.tick_params(axis=\"x\", labelsize=16, colors=INK_SOFT)\nax.tick_params(axis=\"y\", labelsize=0)\nax.set_yticks([])\n\n# Remove spines\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nax.spines[\"left\"].set_visible(False)\nax.spines[\"bottom\"].set_color(INK_SOFT)\n\n# Subtle grid\nax.grid(axis=\"x\", alpha=0.15, linewidth=0.8, color=INK)\n\n# Legend\nlegend = ax.legend(loc=\"lower right\", fontsize=16, framealpha=0.95)\nlegend.get_frame().set_facecolor(ELEVATED_BG)\nlegend.get_frame().set_edgecolor(INK_SOFT)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}