{"spec_id":"heatmap-adjacency","library":"altair","language":"python","code":"\"\"\" anyplot.ai\nheatmap-adjacency: Network Adjacency Matrix Heatmap\nLibrary: altair 6.3.0 | Python 3.14.10\nQuality: 83/100 | Updated: 2026-11-16\n\"\"\"\n\nimport os\n\nimport altair as alt\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\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: sequential ramp (single polarity) runs brand green -> blue\nIMPRINT_SEQ = [\"#009E73\", \"#4467A3\"]\n\n# Columns: set these to your table's column names\nRESEARCHER = \"Researcher\"  # role: source\nPARTNER = \"Co-author\"  # role: target\nSTRENGTH = \"Collaboration strength\"  # role: weight\n\n# Data: replace this block with your own table, e.g. df = edges.pivot(index=..., columns=..., values=...)\n# Academic co-authorship network: 3 departments with 8 members each, nodes ordered by department\nrng = np.random.default_rng(42)\nn_per_dept = 8\nnodes = [f\"{dept}{i + 1:02d}\" for dept in (\"Ph\", \"Bi\", \"Ch\") for i in range(n_per_dept)]\nadj = np.zeros((len(nodes), len(nodes)))\nfor i in range(len(nodes)):\n    for j in range(i + 1, len(nodes)):\n        if i // n_per_dept == j // n_per_dept:\n            weight = rng.uniform(0.45, 1.0) if rng.random() > 0.18 else 0.0\n        else:\n            weight = rng.uniform(0.08, 0.38) if rng.random() > 0.74 else 0.0\n        adj[i, j] = adj[j, i] = weight  # undirected: both triangles filled\ndf = pd.DataFrame(adj, index=nodes, columns=nodes)\n\n# Plot: reads only df and the constants above\nESCAPE = str.maketrans({\".\": \"\\\\.\", \"[\": \"\\\\[\", \"]\": \"\\\\]\", \":\": \"\\\\:\"})\norder = list(df.index)\nlong = (\n    df.rename_axis(index=RESEARCHER, columns=PARTNER)\n    .stack()\n    .rename(STRENGTH)\n    .reset_index()\n    .assign(**{STRENGTH: lambda t: t[STRENGTH].where(t[STRENGTH] > 0)})  # absent edge -> missing\n)\npresent = long.dropna(subset=[STRENGTH])\n\nx_enc = alt.X(PARTNER.translate(ESCAPE), type=\"ordinal\", scale=alt.Scale(domain=order), title=PARTNER)\ny_enc = alt.Y(RESEARCHER.translate(ESCAPE), type=\"ordinal\", scale=alt.Scale(domain=order), title=RESEARCHER)\n\n# Layer 1: every cell as a neutral tile, so an absent edge reads as \"no edge\", never as a weak one\nbase = alt.Chart(long).mark_rect(fill=ELEVATED_BG, stroke=PAGE_BG, strokeWidth=0.5).encode(x=x_enc, y=y_enc)\n\n# Layer 2: present edges, colour intensity = weight\nedges = (\n    alt.Chart(present)\n    .mark_rect(stroke=PAGE_BG, strokeWidth=0.5)\n    .encode(\n        x=x_enc,\n        y=y_enc,\n        color=alt.Color(\n            STRENGTH.translate(ESCAPE),\n            type=\"quantitative\",\n            title=STRENGTH,\n            scale=alt.Scale(range=IMPRINT_SEQ, domain=[0, float(np.nanmax(df.to_numpy()))]),\n            legend=alt.Legend(gradientLength=300, gradientThickness=18),\n        ),\n        tooltip=[\n            alt.Tooltip(RESEARCHER.translate(ESCAPE), type=\"ordinal\", title=RESEARCHER),\n            alt.Tooltip(PARTNER.translate(ESCAPE), type=\"ordinal\", title=PARTNER),\n            alt.Tooltip(STRENGTH.translate(ESCAPE), type=\"quantitative\", title=STRENGTH, format=\".2f\"),\n        ],\n    )\n)\n\n# Group boundaries between departments, derived from the node-name prefixes\ngroups = pd.Series([str(name).rstrip(\"0123456789\") for name in order])\ncuts = groups.index[groups != groups.shift()][1:].tolist()\ncut_df = pd.DataFrame({\"at\": [order[c] for c in cuts]})\nvlines = (\n    alt.Chart(cut_df)\n    .mark_rule(color=INK, strokeDash=[6, 4], strokeWidth=1.2, opacity=0.7, xOffset=-0.5)\n    .encode(x=alt.X(\"at:O\", scale=alt.Scale(domain=order), bandPosition=0, title=PARTNER))\n)\nhlines = (\n    alt.Chart(cut_df)\n    .mark_rule(color=INK, strokeDash=[6, 4], strokeWidth=1.2, opacity=0.7, yOffset=-0.5)\n    .encode(y=alt.Y(\"at:O\", scale=alt.Scale(domain=order), bandPosition=0, title=RESEARCHER))\n)\n\ntitle = \"heatmap-adjacency · python · altair · anyplot.ai\"\nchart = (\n    alt.layer(base, edges, vlines, hlines)\n    .properties(width=368, height=368, title=alt.Title(title, fontSize=16), background=PAGE_BG)\n    .configure_axis(\n        domainColor=INK_SOFT,\n        tickColor=INK_SOFT,\n        grid=False,\n        labelColor=INK_SOFT,\n        titleColor=INK,\n        labelFontSize=10,\n        titleFontSize=12,\n    )\n    .configure_axisX(labelAngle=-45)\n    .configure_title(color=INK)\n    .configure_view(fill=PAGE_BG, stroke=INK_SOFT)\n    .configure_legend(\n        fillColor=ELEVATED_BG,\n        strokeColor=INK_SOFT,\n        labelColor=INK_SOFT,\n        titleColor=INK,\n        titleFontSize=12,\n        labelFontSize=10,\n        padding=8,\n    )\n)\n\n# Save\nchart.save(f\"plot-{THEME}.png\", scale_factor=4.0)\nchart.save(f\"plot-{THEME}.html\")\n\n# Pad (never crop) to the 2400 x 2400 square target\nTARGET = 2400\nimg = Image.open(f\"plot-{THEME}.png\").convert(\"RGB\")\nif img.width > TARGET or img.height > TARGET:\n    raise SystemExit(f\"altair rendered {img.width}x{img.height}, exceeds {TARGET}x{TARGET}; shrink width/height\")\nif img.size != (TARGET, TARGET):\n    canvas = Image.new(\"RGB\", (TARGET, TARGET), PAGE_BG)\n    canvas.paste(img, ((TARGET - img.width) // 2, (TARGET - img.height) // 2))\n    canvas.save(f\"plot-{THEME}.png\")\n"}