{"spec_id":"silhouette-basic","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nsilhouette-basic: Silhouette Plot\nLibrary: matplotlib 3.10.9 | 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\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import load_iris\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 for clusters\nIMPRINT = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\"]\n\n# Data - use iris dataset for realistic clustering example\niris = load_iris()\nX = iris.data\nn_clusters = 3\n\n# Perform clustering\nkmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)\ncluster_labels = kmeans.fit_predict(X)\n\n# Calculate silhouette scores\nsilhouette_avg = silhouette_score(X, cluster_labels)\nsample_silhouette_values = silhouette_samples(X, cluster_labels)\n\n# Plot\nfig, ax = plt.subplots(figsize=(16, 9), facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\ny_lower = 10\nfor i in range(n_clusters):\n    # Get silhouette values for cluster i and sort them\n    ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]\n    ith_cluster_silhouette_values.sort()\n\n    size_cluster_i = ith_cluster_silhouette_values.shape[0]\n    y_upper = y_lower + size_cluster_i\n\n    # Fill horizontal bars for each sample\n    ax.fill_betweenx(\n        np.arange(y_lower, y_upper),\n        0,\n        ith_cluster_silhouette_values,\n        facecolor=IMPRINT[i % len(IMPRINT)],\n        edgecolor=IMPRINT[i % len(IMPRINT)],\n        alpha=0.8,\n    )\n\n    # Annotate cluster with its average silhouette score\n    cluster_avg = np.mean(ith_cluster_silhouette_values)\n    ax.text(\n        -0.05,\n        y_lower + 0.5 * size_cluster_i,\n        f\"Cluster {i}\\n(avg: {cluster_avg:.2f})\",\n        fontsize=16,\n        verticalalignment=\"center\",\n        horizontalalignment=\"right\",\n        color=INK,\n    )\n\n    y_lower = y_upper + 10  # Gap between clusters\n\n# Add vertical line for average silhouette score\nax.axvline(x=silhouette_avg, color=INK_SOFT, linestyle=\"--\", linewidth=3, label=f\"Average Score: {silhouette_avg:.2f}\")\n\n# Style\nax.set_xlabel(\"Silhouette Coefficient\", fontsize=20, color=INK)\nax.set_ylabel(\"Sample Index (by Cluster)\", fontsize=20, color=INK)\nax.set_title(\"silhouette-basic · matplotlib · anyplot.ai\", fontsize=24, fontweight=\"medium\", color=INK)\n\nax.tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT)\nax.set_xlim([-0.2, 1.0])\nax.set_ylim([0, y_lower])\nax.set_yticks([])  # Hide y-axis ticks as they're not meaningful\n\n# Spine styling\nfor spine in [\"top\", \"right\"]:\n    ax.spines[spine].set_visible(False)\nfor spine in [\"left\", \"bottom\"]:\n    ax.spines[spine].set_color(INK_SOFT)\n\n# Legend\nleg = ax.legend(fontsize=16, loc=\"lower right\")\nif leg:\n    leg.get_frame().set_facecolor(ELEVATED_BG)\n    leg.get_frame().set_edgecolor(INK_SOFT)\n    leg.get_frame().set_linewidth(1)\n    plt.setp(leg.get_texts(), color=INK_SOFT)\n\nax.grid(True, alpha=0.15, linestyle=\"-\", axis=\"x\", color=INK_SOFT, linewidth=0.8)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}