{"spec_id":"scatter-embedding","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nscatter-embedding: t-SNE and UMAP Embedding Visualization\nLibrary: matplotlib 3.11.1 | Python 3.13.14\nQuality: 93/100 | Updated: 2026-08-11\n\"\"\"\n\nimport os\nimport sys\n\n\nsys.path.pop(0)\nimport matplotlib.patheffects as pe\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.datasets import make_blobs\nfrom sklearn.manifold import TSNE\n\n\n# Theme\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\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\nIMPRINT = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\"]\n\nCLUSTER_LABELS = [\"Finance\", \"Healthcare\", \"Technology\", \"Sports\", \"Politics\", \"Science\", \"Entertainment\"]\n# 7 series sits at the CVD discrimination floor (Imprint palette) — pair each color\n# with a distinct marker shape for redundant encoding, per the style guide's\n# color-restraint table.\nMARKERS = [\"o\", \"s\", \"^\", \"D\", \"v\", \"P\", \"X\"]\n\n# Data — 1050 document embeddings (150 per topic) in 50-dimensional space\n# cluster_std=3.3 leaves some boundary overlap/noise between neighboring topics,\n# matching the real-world embedding-quality-checking use case this spec targets\nnp.random.seed(42)\nX_high, labels = make_blobs(n_samples=1050, n_features=50, centers=7, cluster_std=3.3, random_state=42)\ntsne = TSNE(n_components=2, perplexity=30, random_state=42)\nX_2d = tsne.fit_transform(X_high)\n\n# Plot\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\nfor i, (label, color, marker) in enumerate(zip(CLUSTER_LABELS, IMPRINT, MARKERS, strict=False)):\n    mask = labels == i\n    ax.scatter(X_2d[mask, 0], X_2d[mask, 1], c=color, s=90, alpha=0.65, edgecolors=\"none\", marker=marker, label=label)\n\n# Centroid annotations\nfor i, label in enumerate(CLUSTER_LABELS):\n    mask = labels == i\n    cx, cy = X_2d[mask, 0].mean(), X_2d[mask, 1].mean()\n    txt = ax.text(\n        cx,\n        cy,\n        label,\n        fontsize=9,\n        fontweight=\"bold\",\n        color=INK,\n        ha=\"center\",\n        va=\"center\",\n        bbox={\n            \"facecolor\": ELEVATED_BG,\n            \"edgecolor\": INK_SOFT,\n            \"alpha\": 0.85,\n            \"boxstyle\": \"round,pad=0.3\",\n            \"linewidth\": 0.8,\n        },\n    )\n    # PathEffects halo keeps the bold label crisp against the box even where\n    # dense, overlapping markers sit directly beneath the centroid text\n    txt.set_path_effects([pe.withStroke(linewidth=2, foreground=ELEVATED_BG)])\n\n# Outlier callout — surfaces the point furthest from its own cluster centroid,\n# the kind of embedding-quality check this plot type exists to support (DE-03)\noutlier_mask = labels == 5\noutlier_centroid = np.array([X_2d[outlier_mask, 0].mean(), X_2d[outlier_mask, 1].mean()])\noutlier_dists = np.linalg.norm(X_2d[outlier_mask] - outlier_centroid, axis=1)\noutlier_point = X_2d[outlier_mask][np.argmax(outlier_dists)]\nax.annotate(\n    \"farthest from centroid\",\n    xy=(outlier_point[0], outlier_point[1]),\n    xytext=(18, -16),\n    textcoords=\"offset points\",\n    fontsize=8,\n    color=INK_MUTED,\n    arrowprops={\"arrowstyle\": \"->\", \"color\": INK_MUTED, \"linewidth\": 1},\n)\n\n# Style\nax.set_xlabel(\"t-SNE 1\", fontsize=10, color=INK)\nax.set_ylabel(\"t-SNE 2\", fontsize=10, color=INK)\nax.set_title(\n    \"Document Topic Embeddings · scatter-embedding · python · matplotlib · anyplot.ai\",\n    fontsize=10,\n    fontweight=\"medium\",\n    color=INK,\n)\nax.tick_params(axis=\"both\", length=0, colors=INK_SOFT, labelbottom=False, labelleft=False)\nax.grid(True, alpha=0.15, color=INK, linewidth=0.8)\n\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nfor s in (\"left\", \"bottom\"):\n    ax.spines[s].set_color(INK_SOFT)\n\n# Legend\nleg = ax.legend(fontsize=8, loc=\"lower right\", framealpha=0.9, title=\"Topic\", title_fontsize=9)\nleg.get_frame().set_facecolor(ELEVATED_BG)\nleg.get_frame().set_edgecolor(INK_SOFT)\nplt.setp(leg.get_texts(), color=INK_SOFT)\nleg.get_title().set_color(INK_SOFT)\n\n# Algorithm subtitle\nfig.text(\n    0.5,\n    0.01,\n    \"t-SNE (perplexity=30)  ·  50-dimensional document embeddings  ·  7 topic clusters\",\n    ha=\"center\",\n    va=\"bottom\",\n    fontsize=8,\n    color=INK_MUTED,\n)\n\nplt.tight_layout(rect=[0, 0.04, 1, 1])\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}