{"spec_id":"heatmap-adjacency","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nheatmap-adjacency: Network Adjacency Matrix Heatmap\nLibrary: bokeh 3.10.2 | Python 3.14.10\nQuality: 82/100 | Updated: 2026-11-15\n\"\"\"\n\n# ruff: noqa: E402\nimport sys\n\n\n# Prevent this script's directory from shadowing the installed bokeh package\n_script_dir = sys.path[0] if sys.path else \"\"\nif _script_dir and \"implementations/python\" in _script_dir:\n    sys.path = sys.path[1:]\n\nimport math\nimport os\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom bokeh.io import output_file, save\nfrom bokeh.models import BasicTicker, ColorBar, ColumnDataSource, LinearColorMapper\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\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\"\nNAN_COLOR = \"#E8E5DE\" if THEME == \"light\" else \"#252520\"\n\n# Imprint palette: all eight positions in canonical order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n\ndef _lerp_hex(c0, c1, t):\n    a = [int(c0[i : i + 2], 16) for i in (1, 3, 5)]\n    b = [int(c1[i : i + 2], 16) for i in (1, 3, 5)]\n    return \"#\" + \"\".join(f\"{round(x + (y - x) * t):02X}\" for x, y in zip(a, b, strict=False))\n\n\n# Imprint sequential ramp (single polarity): green to blue\nIMPRINT_SEQ = [_lerp_hex(\"#009E73\", \"#4467A3\", t / 255) for t in range(256)]\n\n# Columns: set these to your table's column names\nSOURCE = \"Source researcher\"  # role: source\nTARGET = \"Target researcher\"  # role: target\nWEIGHT = \"Connection strength\"  # role: weight\n\n# Data: replace this block with your own edge list, for example df = pd.read_csv(\"edges.csv\")\n# 24 researchers in 4 departments (ordered by department); each undirected edge listed once\nnp.random.seed(42)\ndept_codes = [\"Phy\", \"Chem\", \"Bio\", \"Math\"]\nnames = [f\"{code}{i:02d}\" for code in dept_codes for i in range(1, 7)]\ndept_of = {name: k // 6 for k, name in enumerate(names)}\nedges = []\nfor a in range(len(names)):\n    for b in range(a + 1, len(names)):\n        same_dept = dept_of[names[a]] == dept_of[names[b]]\n        if same_dept and np.random.rand() < 0.80:\n            edges.append((names[a], names[b], np.random.uniform(0.5, 1.0)))\n        elif not same_dept and np.random.rand() < 0.08:\n            edges.append((names[a], names[b], np.random.uniform(0.1, 0.4)))\ndf = pd.DataFrame(edges, columns=[SOURCE, TARGET, WEIGHT])\n\n# Plot: reads only df and the constants above\n# Node order: first appearance, sources first, which keeps departments contiguous\nnodes = list(pd.unique(pd.concat([df[SOURCE], df[TARGET]], ignore_index=True)))\n# Undirected graph: fill both triangles\ncells = pd.concat(\n    [df.rename(columns={SOURCE: \"row\", TARGET: \"col\"}), df.rename(columns={SOURCE: \"col\", TARGET: \"row\"})],\n    ignore_index=True,\n)\nsource = ColumnDataSource(cells)\n\nmapper = LinearColorMapper(palette=IMPRINT_SEQ, low=df[WEIGHT].min(), high=df[WEIGHT].max(), nan_color=NAN_COLOR)\n\np = figure(\n    width=2400,\n    height=2400,\n    x_range=nodes,\n    y_range=list(reversed(nodes)),\n    toolbar_location=None,\n    title=\"Researcher Collaboration · heatmap-adjacency · python · bokeh · anyplot.ai\",\n    x_axis_label=TARGET,\n    y_axis_label=SOURCE,\n    min_border_top=90,\n    min_border_bottom=60,\n    min_border_left=60,\n    min_border_right=60,\n)\n\n# Absent edges: background cells in a distinct tone, so they never read as weak edges\ngrid = pd.MultiIndex.from_product([nodes, nodes], names=[\"row\", \"col\"]).to_frame(index=False)\np.rect(x=\"col\", y=\"row\", width=1, height=1, source=ColumnDataSource(grid), fill_color=NAN_COLOR, line_color=None)\n\n# Edge cells colored by weight\np.rect(\n    x=\"col\",\n    y=\"row\",\n    width=1,\n    height=1,\n    source=source,\n    fill_color={\"field\": WEIGHT, \"transform\": mapper},\n    line_color=None,\n)\n\ncolorbar = ColorBar(\n    color_mapper=mapper,\n    ticker=BasicTicker(desired_num_ticks=6),\n    label_standoff=16,\n    border_line_color=None,\n    location=(0, 0),\n    title=WEIGHT,\n    title_text_font_size=\"22pt\",\n    title_text_color=INK,\n    major_label_text_font_size=\"20pt\",\n    major_label_text_color=INK_SOFT,\n    background_fill_color=PAGE_BG,\n    width=50,\n)\np.add_layout(colorbar, \"right\")\n\n# Style\np.title.text_font_size = \"34pt\"\np.title.text_color = INK\np.title.text_font_style = \"normal\"\n\np.xaxis.axis_label_text_font_size = \"26pt\"\np.yaxis.axis_label_text_font_size = \"26pt\"\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_color = INK\n\np.xaxis.major_label_text_font_size = \"20pt\"\np.yaxis.major_label_text_font_size = \"20pt\"\np.xaxis.major_label_text_color = INK_SOFT\np.yaxis.major_label_text_color = INK_SOFT\np.xaxis.major_label_orientation = math.pi / 3\n\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = INK_SOFT\n\np.xaxis.axis_line_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\np.xaxis.major_tick_line_color = INK_SOFT\np.yaxis.major_tick_line_color = INK_SOFT\n\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = None\n\n# Save HTML\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with headless Chrome via Selenium\nW, H = 2400, 2400\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()}\")\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"}