{"spec_id":"heatmap-adjacency","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nheatmap-adjacency: Network Adjacency Matrix Heatmap\nLibrary: matplotlib 3.11.2 | Python 3.14.10\nQuality: 87/100 | Updated: 2026-11-15\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom matplotlib.transforms import blended_transform_factory\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, one per community in order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nimprint_seq = LinearSegmentedColormap.from_list(\"imprint_seq\", [\"#009E73\", \"#4467A3\"])\nimprint_seq.set_bad(PAGE_BG)  # absent edges take the page tone\n\n# Columns: the matrix is the table, only the color bar needs a name\nSOURCE = \"Source node (sorted by community)\"  # role: source\nTARGET = \"Target node (sorted by community)\"  # role: target\nWEIGHT = \"Connection strength\"  # role: weight\n\n# Data: replace this block with your own labeled square matrix, for example df = pd.read_csv(\"edges.csv\", index_col=0)\n# Research collaboration network; node labels start with the community, nodes are sorted by community\nnp.random.seed(42)\ncommunities = {\"Neuro\": 10, \"CS\": 12, \"Psych\": 8}\nlabels = [f\"{name} {k:02d}\" for name, size in communities.items() for k in range(1, size + 1)]\ngroup = np.repeat(list(communities), list(communities.values()))\nsame = group[:, None] == group[None, :]\npresent = np.triu(np.random.random((len(labels), len(labels))) < np.where(same, 0.72, 0.12), k=1)\nstrength = np.where(same, np.random.uniform(0.5, 1.0, same.shape), np.random.uniform(0.05, 0.3, same.shape))\nupper = np.where(present, strength, 0.0)\ndf = pd.DataFrame(upper + upper.T, index=labels, columns=labels)\n\n# Plot: reads only df and the constants above\nmatrix = df.to_numpy()\nnodes = [str(node) for node in df.index]\ngroups = pd.Series([node.split()[0] for node in nodes])\nsizes = groups.groupby(groups, sort=False).size()\nedges = np.concatenate([[0], np.cumsum(sizes.to_numpy())])\n\nfig, ax = plt.subplots(figsize=(6, 6), dpi=400, facecolor=PAGE_BG, layout=\"constrained\")\nax.set_facecolor(PAGE_BG)\nim = ax.imshow(\n    np.where(matrix == 0, np.nan, matrix), cmap=imprint_seq, vmin=0, vmax=np.nanmax(matrix), interpolation=\"nearest\"\n)\n\n# Community boundary lines\nfor b in edges[1:-1]:\n    ax.axhline(b - 0.5, color=INK, linewidth=1.2, alpha=0.5)\n    ax.axvline(b - 0.5, color=INK, linewidth=1.2, alpha=0.5)\n\n# Community names above the matrix: data x, axes y\ntrans = blended_transform_factory(ax.transData, ax.transAxes)\nfor i, name in enumerate(sizes.index):\n    ax.text(\n        (edges[i] + edges[i + 1] - 1) / 2,\n        1.01,\n        name,\n        transform=trans,\n        ha=\"center\",\n        va=\"bottom\",\n        fontsize=10,\n        fontweight=\"bold\",\n        color=IMPRINT_PALETTE[i % len(IMPRINT_PALETTE)],\n    )\n\n# Style\nax.set_xticks(range(len(nodes)), nodes, rotation=90, fontsize=6.5, color=INK_SOFT)\nax.set_yticks(range(len(nodes)), nodes, fontsize=6.5, color=INK_SOFT)\nax.tick_params(length=0, pad=2)\nfor spine in ax.spines.values():\n    spine.set_edgecolor(INK_SOFT)\n    spine.set_linewidth(0.8)\nax.set_xlabel(TARGET, fontsize=10, color=INK)\nax.set_ylabel(SOURCE, fontsize=10, color=INK)\nax.set_title(\n    \"heatmap-adjacency · python · matplotlib · anyplot.ai\", fontsize=12, fontweight=\"medium\", color=INK, pad=24\n)\n\ncbar = fig.colorbar(im, ax=ax, shrink=0.75, pad=0.02)\ncbar.set_label(WEIGHT, fontsize=10, color=INK)\ncbar.ax.tick_params(labelsize=8, labelcolor=INK_SOFT, color=INK_SOFT)\ncbar.outline.set_edgecolor(INK_SOFT)\n\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)\n"}