{"spec_id":"scatter-embedding","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nscatter-embedding: t-SNE and UMAP Embedding Visualization\nLibrary: bokeh 3.9.2 | Python 3.13.14\nQuality: 91/100 | Updated: 2026-08-11\n\"\"\"\n\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\n\nsys.path = [p for p in sys.path if \"implementations\" not in p]\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, Label, Range1d, Title\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom sklearn.datasets import make_blobs\nfrom sklearn.manifold import TSNE\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# Imprint palette — canonical categorical order, first series always brand green\nIMPRINT = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\"]\nCLUSTER_NAMES = [\n    \"Machine Learning\",\n    \"Data Engineering\",\n    \"Natural Language Processing\",\n    \"Computer Vision\",\n    \"Distributed Systems\",\n    \"Bioinformatics\",\n]\n\n# Data — synthetic high-dimensional document embeddings reduced via t-SNE.\n# Cluster centers and spreads are varied (rather than uniform) to mimic the\n# ambiguity real embeddings show: Data Engineering is nudged close to Machine\n# Learning so the two overlap slightly, and cluster_std differs per group.\nnp.random.seed(42)\nn_features = 20\ncenters = np.random.uniform(-10, 10, size=(6, n_features))\ncenters[1] = centers[0] + np.random.normal(scale=1.5, size=n_features)\ncluster_std = [2.5, 3.2, 2.1, 2.9, 1.9, 3.5]\nX, labels = make_blobs(n_samples=900, n_features=n_features, centers=centers, cluster_std=cluster_std)\ntsne = TSNE(n_components=2, perplexity=30, random_state=42, max_iter=1000)\nembedding = tsne.fit_transform(X)\n\n# Fit axes to the 2nd-98th percentile of the data rather than the raw min/max —\n# a handful of t-SNE stragglers otherwise inflate the range and leave large\n# empty margins on one side of the canvas (VQ-05 in the previous review).\nx_lo, x_hi = np.percentile(embedding[:, 0], [2, 98])\ny_lo, y_hi = np.percentile(embedding[:, 1], [2, 98])\nx_pad = (x_hi - x_lo) * 0.10\ny_pad = (y_hi - y_lo) * 0.10\n\n# Plot — canonical 3200x1800 landscape canvas (Step 0 contract)\nW, H = 3200, 1800\np = figure(\n    width=W,\n    height=H,\n    title=\"NLP Document Clusters · scatter-embedding · python · bokeh · anyplot.ai\",\n    x_range=Range1d(x_lo - x_pad, x_hi + x_pad),\n    y_range=Range1d(y_lo - y_pad, y_hi + y_pad),\n    tools=\"pan,wheel_zoom,box_zoom,reset,hover\",\n    tooltips=[(\"Cluster\", \"@cluster\")],\n    toolbar_location=None,  # default toolbar shrinks the saved PNG below `height=`\n    min_border_bottom=160,\n    min_border_left=180,\n    min_border_top=140,  # extra room for the two-line title + subtitle stack\n    min_border_right=50,\n)\n\np.add_layout(\n    Title(text=\"t-SNE (perplexity=30)\", text_font_size=\"30pt\", text_color=INK_SOFT, text_font_style=\"italic\"), \"above\"\n)\n\n# Chrome\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = None\n\np.title.text_color = INK\np.title.text_font_size = \"50pt\"\np.title.text_font_style = \"bold\"\n\np.xaxis.axis_label = \"t-SNE 1\"\np.yaxis.axis_label = \"t-SNE 2\"\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_color = INK\np.xaxis.axis_label_text_font_size = \"42pt\"\np.yaxis.axis_label_text_font_size = \"42pt\"\n\n# Hide tick labels — embedding coordinates are not directly interpretable\np.xaxis.major_label_text_alpha = 0\np.yaxis.major_label_text_alpha = 0\np.xaxis.major_tick_line_alpha = 0\np.yaxis.major_tick_line_alpha = 0\np.xaxis.minor_tick_line_alpha = 0\np.yaxis.minor_tick_line_alpha = 0\n\np.xaxis.axis_line_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\n\np.xgrid.grid_line_color = INK\np.ygrid.grid_line_color = INK\np.xgrid.grid_line_alpha = 0.15\np.ygrid.grid_line_alpha = 0.15\n\n# One scatter call per cluster so Bokeh assigns legend entries\nfor i, (name, color) in enumerate(zip(CLUSTER_NAMES, IMPRINT, strict=False)):\n    mask = labels == i\n    source = ColumnDataSource(\n        data={\"x\": embedding[mask, 0], \"y\": embedding[mask, 1], \"cluster\": [name] * int(mask.sum())}\n    )\n    p.scatter(\n        x=\"x\",\n        y=\"y\",\n        source=source,\n        color=color,\n        size=14,\n        alpha=0.40,\n        line_color=PAGE_BG,\n        line_width=0.6,\n        legend_label=name,\n    )\n\n# Centroid annotations — label each cluster at its centre for storytelling\nfor i, (name, color) in enumerate(zip(CLUSTER_NAMES, IMPRINT, strict=False)):\n    mask = labels == i\n    cx = float(embedding[mask, 0].mean())\n    cy = float(embedding[mask, 1].mean())\n    centroid_label = Label(\n        x=cx,\n        y=cy,\n        text=name,\n        text_font_size=\"26pt\",\n        text_color=INK,\n        text_align=\"center\",\n        text_baseline=\"middle\",\n        background_fill_color=ELEVATED_BG,\n        background_fill_alpha=0.80,\n        border_line_color=color,\n        border_line_width=2,\n        border_line_alpha=0.7,\n        padding=8,\n    )\n    p.add_layout(centroid_label)\n\n# Style legend\np.legend.background_fill_color = ELEVATED_BG\np.legend.border_line_color = INK_SOFT\np.legend.label_text_color = INK_SOFT\np.legend.label_text_font_size = \"34pt\"\np.legend.glyph_height = 34\np.legend.glyph_width = 34\np.legend.location = \"top_right\"\np.legend.click_policy = \"hide\"\n\n# Save HTML\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot via headless Chrome\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\n# Headless Chrome's --window-size sets the OUTER window, which still reserves a\n# phantom title-bar height even headless — pin the viewport exactly via CDP.\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ntime.sleep(3)\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}