{"spec_id":"heatmap-adjacency","library":"plotly","language":"python","code":"\"\"\" anyplot.ai\nheatmap-adjacency: Network Adjacency Matrix Heatmap\nLibrary: plotly 7.1.0 | Python 3.14.10\nQuality: 83/100 | Updated: 2026-11-16\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\n\n# Imprint palette: all eight positions in canonical order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Imprint sequential colormap (single polarity): brand green to blue\nIMPRINT_SEQ = [[0.0, \"#009E73\"], [1.0, \"#4467A3\"]]\n\n# Constants\nABSENT_BELOW = 0.05  # co-occurrence below this strength counts as \"no edge\" and stays background-colored\n\n# Columns: set these to your table's labels\nSOURCE = \"Source term\"  # role: source\nTARGET = \"Target term\"  # role: target\nWEIGHT = \"Co-occurrence strength\"  # role: weight\n\n# Data: replace this block with your own square matrix, rows and columns indexed by (group, term), nodes ordered by group\nnp.random.seed(42)\ndomains = {\n    \"Machine Learning\": [\"neural net\", \"gradient\", \"backprop\", \"optimizer\", \"dropout\", \"attention\"],\n    \"Neuroscience\": [\"synapse\", \"cortex\", \"dendrite\", \"neuron\", \"hippocampus\", \"axon\"],\n    \"Genomics\": [\"DNA\", \"RNA\", \"gene\", \"protein\", \"chromosome\", \"mutation\"],\n    \"Chemistry\": [\"molecule\", \"catalyst\", \"reaction\", \"bond\", \"polymer\", \"enzyme\"],\n    \"Physics\": [\"quantum\", \"photon\", \"entropy\", \"wave\", \"spin\", \"field\"],\n}\npairs = [(domain, term) for domain, terms in domains.items() for term in terms]\nn_nodes = len(pairs)\nweights = np.zeros((n_nodes, n_nodes))\nfor i in range(n_nodes):\n    for j in range(i + 1, n_nodes):\n        if pairs[i][0] == pairs[j][0]:\n            weights[i, j] = weights[j, i] = np.random.uniform(0.55, 1.0)\n        else:\n            weights[i, j] = weights[j, i] = np.random.uniform(0.0, 0.12)\nindex = pd.MultiIndex.from_tuples(pairs, names=[\"Research domain\", SOURCE])\ndf = pd.DataFrame(weights, index=index, columns=pd.MultiIndex.from_tuples(pairs, names=[\"Research domain\", TARGET]))\n\n# Plot: reads only df and the constants above\nterms = df.index.get_level_values(-1)\ngroups = df.index.get_level_values(0)  # a flat index has one level: no group boundaries\nn = len(df)\nboundaries = [i for i in range(1, n) if groups[i] != groups[i - 1]]\n\n# Absent edges become gaps, so the page background shows through and cannot be mistaken for a weak edge\nz = df.to_numpy(dtype=float)\nz = np.where(z < ABSENT_BELOW, np.nan, z)\n\nfig = go.Figure(\n    go.Heatmap(\n        z=z,\n        x=terms,\n        y=terms,\n        colorscale=IMPRINT_SEQ,\n        zmin=0,\n        zmax=np.nanmax(z),\n        xgap=1,\n        ygap=1,\n        colorbar={\n            \"title\": {\"text\": WEIGHT.replace(\" \", \"<br>\", 1), \"font\": {\"size\": 12, \"color\": INK}, \"side\": \"right\"},\n            \"tickfont\": {\"size\": 10, \"color\": INK_SOFT},\n            \"thickness\": 14,\n            \"len\": 0.75,\n            \"outlinewidth\": 0,\n        },\n        hoverongaps=False,\n        hovertemplate=\"%{y} ↔ %{x}<br>Strength: %{z:.2f}<extra></extra>\",\n    )\n)\n\n# Cluster boundary lines separating research domains\nfor b in boundaries:\n    fig.add_shape(type=\"line\", x0=b - 0.5, x1=b - 0.5, y0=-0.5, y1=n - 0.5, line={\"color\": INK, \"width\": 1.5})\n    fig.add_shape(type=\"line\", x0=-0.5, x1=n - 0.5, y0=b - 0.5, y1=b - 0.5, line={\"color\": INK, \"width\": 1.5})\n\n# Style\ntitle = \"Research Domain Co-occurrence · heatmap-adjacency · python · plotly · anyplot.ai\"\ntitle_size = max(11, round(16 * min(1.0, 67 / len(title))))\nfig.update_layout(\n    autosize=False,\n    width=600,\n    height=600,\n    title={\"text\": title, \"font\": {\"size\": title_size, \"color\": INK}, \"x\": 0.5, \"xanchor\": \"center\"},\n    paper_bgcolor=PAGE_BG,\n    plot_bgcolor=PAGE_BG,\n    font={\"color\": INK},\n    xaxis={\n        \"title\": {\"text\": TARGET, \"font\": {\"size\": 12, \"color\": INK}},\n        \"tickfont\": {\"size\": 10, \"color\": INK_SOFT},\n        \"tickangle\": -45,\n        \"showgrid\": False,\n        \"zeroline\": False,\n        \"showline\": False,\n        \"constrain\": \"domain\",\n    },\n    yaxis={\n        \"title\": {\"text\": SOURCE, \"font\": {\"size\": 12, \"color\": INK}},\n        \"tickfont\": {\"size\": 10, \"color\": INK_SOFT},\n        \"showgrid\": False,\n        \"zeroline\": False,\n        \"showline\": False,\n        \"autorange\": \"reversed\",\n        \"scaleanchor\": \"x\",\n        \"constrain\": \"domain\",\n    },\n    margin={\"l\": 100, \"r\": 40, \"t\": 60, \"b\": 105},\n)\n\n# Save\nfig.write_image(f\"plot-{THEME}.png\", width=600, height=600, scale=4)\nfig.write_html(f\"plot-{THEME}.html\", include_plotlyjs=\"cdn\")\n"}