Source code for hatvis.plotting.matrix

"""Matrix-based views: incidence matrix, PAOH, UpSet, house of quality, similarity heatmap."""

from __future__ import annotations

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Polygon, Rectangle

from ..core import Hypergraph
from ._style import BRAND, GRAY, INK, PALETTE, color_cycle, get_ax

__all__ = ["plot_incidence", "plot_paoh", "plot_upset", "plot_house_of_quality", "plot_similarity_matrix"]

BRAND_CMAP = LinearSegmentedColormap.from_list("hatvis", ["#FFFFFF", "#9CC3E6", BRAND, "#14304A"])


def _orders(H, order, weighted):
    from ..seriation import seriate
    if order is None or order == "none":
        return H.nodes, H.edges
    if isinstance(order, tuple):
        return list(order[0]), list(order[1])
    return seriate(H, order, weighted=weighted)


[docs] def plot_incidence(H: Hypergraph, order="barycentric", *, ax=None, weighted: bool = True, transpose: bool = False, biclusters=None, labels: bool = True, cmap=None, colorbar: bool = False, grid: bool = True, node_groups: str | None = None, label_size: float = 7, title: str | None = None): """Incidence matrix as a heat map, optionally seriated and with highlighted biclusters. ``order``: ``"barycentric"`` (HAT-VIS iteration), ``"correspondence"``, ``"hierarchical"``, ``None`` or an explicit ``(row_labels, col_labels)`` tuple. ``transpose=True`` puts the hyperedges in rows (as in the manufacturing-space figure of Nagy et al. 2022). ``biclusters`` is the output of :func:`hatvis.seriation.bicluster_blocks`; each block is outlined by the rectangle spanning its rows and columns in the current order. ``node_groups`` colors the vertex tick labels by a ``node_data`` column. """ ax = get_ax(ax, figsize=(7, 5)) rows, cols = _orders(H, order, weighted) M = H.to_dataframe(weighted=weighted) if weighted: M = M * H.weights[None, :] M = M.loc[rows, cols] if transpose: M = M.T X = M.to_numpy() im = ax.imshow(X, aspect="auto", cmap=cmap or BRAND_CMAP, interpolation="nearest", vmin=0) if grid: ax.set_xticks(np.arange(-0.5, X.shape[1], 1), minor=True) ax.set_yticks(np.arange(-0.5, X.shape[0], 1), minor=True) ax.grid(which="minor", color="#E3E7EC", lw=0.4) ax.tick_params(which="minor", length=0) if labels: ax.set_xticks(range(X.shape[1]), [str(c) for c in M.columns], rotation=90, fontsize=label_size) ax.set_yticks(range(X.shape[0]), [str(r) for r in M.index], fontsize=label_size) if node_groups is not None and node_groups in H.node_data: cats = list(dict.fromkeys(H.node_data[node_groups].tolist())) cmapg = dict(zip(cats, color_cycle(len(cats)), strict=True)) ticks = ax.get_xticklabels() if transpose else ax.get_yticklabels() for t in ticks: t.set_color(cmapg.get(H.node_data.loc[_cast(t.get_text(), H.nodes), node_groups], INK)) else: ax.set_xticks([]) ax.set_yticks([]) if biclusters: rpos = {str(r): k for k, r in enumerate(M.index)} cpos = {str(c): k for k, c in enumerate(M.columns)} for k, blk in enumerate(biclusters): rr, cc = (blk["edges"], blk["nodes"]) if transpose else (blk["nodes"], blk["edges"]) ri = [rpos[str(r)] for r in rr] ci = [cpos[str(c)] for c in cc] col = PALETTE[(k + 1) % len(PALETTE)] ax.add_patch(Rectangle((min(ci) - 0.5, min(ri) - 0.5), max(ci) - min(ci) + 1, max(ri) - min(ri) + 1, fill=False, edgecolor=col, lw=2.0, ls="--" if k else "-", zorder=5)) ax.set_xlabel("vertices" if transpose else "hyperedges") ax.set_ylabel("hyperedges" if transpose else "vertices") if colorbar: plt.colorbar(im, ax=ax, fraction=0.04, label="incidence value") if title: ax.set_title(title) return ax
def _cast(text, labels): for v in labels: if str(v) == text: return v return text
[docs] def plot_paoh(H: Hypergraph, *, ax=None, time: str | None = None, row_order="barycentric", edge_color=None, labels: bool = True, label_size: float = 7, title: str | None = None): """Parallel Aggregated Ordered Hypergraph (PAOH) view (Valdivia et al. 2021). Vertices are horizontal lines (rows), every hyperedge is a vertical line with dots at its members. With ``time`` (an ``edge_data`` column) the columns are grouped by time stamp and separated by gaps, which makes the evolution of a dynamic hypergraph readable without any node-link clutter. """ from ..seriation import seriate ax = get_ax(ax, figsize=(8, 4.5)) rows = seriate(H, row_order)[0] if isinstance(row_order, str) and row_order != "none" else ( H.nodes if row_order in (None, "none") else list(row_order)) rpos = {v: k for k, v in enumerate(rows)} ed = H.edge_dict() if time is not None: groups = H.edge_data[time] tvals = sorted(pd.unique(groups)) seq = [] for t in tvals: es = [e for e in H.edges if groups[e] == t] es.sort(key=lambda e: min((rpos[v] for v in ed[e]), default=0)) seq.append((t, es)) else: es = sorted(H.edges, key=lambda e: (min((rpos[v] for v in ed[e]), default=0), -len(ed[e]))) seq = [(None, es)] if edge_color is None: ecol = dict(zip(H.edges, color_cycle(H.n_edges), strict=True)) if time is None else None elif isinstance(edge_color, str) and edge_color in H.edge_data: cats = list(dict.fromkeys(H.edge_data[edge_color])) cm = dict(zip(cats, color_cycle(len(cats)), strict=True)) ecol = {e: cm[H.edge_data.loc[e, edge_color]] for e in H.edges} else: ecol = dict.fromkeys(H.edges, edge_color) x = 0.0 xticks, xlabels = [], [] for t, es in seq: start = x for k, e in enumerate(es): ys = sorted(rpos[v] for v in ed[e]) col = ecol[e] if ecol else PALETTE[k % len(PALETTE)] if ys: ax.plot([x, x], [ys[0], ys[-1]], color=col, lw=1.6, zorder=2) ax.scatter([x] * len(ys), ys, s=26, color=col, zorder=3, edgecolors="white", lw=0.5) x += 1 if t is not None: xticks.append((start + x - 1) / 2) xlabels.append(str(t)) ax.axvspan(start - 0.5, x - 0.5, color="#F4F6F8", zorder=0) x += 1.0 for k in range(len(rows)): ax.axhline(k, color="#E3E7EC", lw=0.6, zorder=1) ax.set_ylim(len(rows) - 0.5, -0.5) ax.set_xlim(-1, x) if labels: ax.set_yticks(range(len(rows)), [str(v) for v in rows], fontsize=label_size) else: ax.set_yticks([]) if time is not None: ax.set_xticks(xticks, xlabels, fontsize=label_size + 1) ax.set_xlabel(time) else: ax.set_xticks([]) ax.set_xlabel("hyperedges") for s in ("top", "right"): ax.spines[s].set_visible(False) if title: ax.set_title(title) return ax
[docs] def plot_upset(H: Hypergraph, by: str = "edges", max_bars: int = 20, weighted: bool = True, fig=None, title: str | None = None): """UpSet plot (Lex et al. 2014) of a hypergraph. ``by="edges"``: one column per distinct vertex set (hyperedge pattern), bar height = total weight (or multiplicity) of the hyperedges with that set, dot matrix = the member vertices, horizontal bars = vertex degrees. This is the natural view of frequent itemsets. ``by="nodes"``: the dual view, one column per distinct membership pattern of the vertices. Returns the figure and a dict of axes. """ G = H if by == "edges" else H.dual() w = G.weights if weighted else np.ones(G.n_edges) agg: dict[frozenset, float] = {} for s, wi in zip(G.edge_sets(), w, strict=True): agg[s] = agg.get(s, 0.0) + float(wi) items = sorted(agg.items(), key=lambda kv: (-kv[1], -len(kv[0]), sorted(map(str, kv[0]))))[:max_bars] elems = [v for v in G.nodes if any(v in s for s, _ in items)] deg = {v: sum(val for s, val in items if v in s) for v in elems} elems.sort(key=lambda v: -deg[v]) fig = fig or plt.figure(figsize=(max(6, 0.38 * len(items) + 2.5), 2.2 + 0.28 * len(elems) + 1.6)) gs = fig.add_gridspec(2, 2, width_ratios=[1.3, 4], height_ratios=[2, max(len(elems), 1) * 0.28 + 0.4], wspace=0.32, hspace=0.03) axb = fig.add_subplot(gs[0, 1]) axm = fig.add_subplot(gs[1, 1], sharex=axb) axs = fig.add_subplot(gs[1, 0]) xs = np.arange(len(items)) axb.bar(xs, [val for _, val in items], color=BRAND, width=0.6) axb.set_ylabel("weight" if weighted else "count") axb.tick_params(labelbottom=False) for s in ("top", "right"): axb.spines[s].set_visible(False) ypos = {v: k for k, v in enumerate(elems)} for x, (s, _) in zip(xs, items, strict=True): axm.scatter([x] * len(elems), range(len(elems)), s=40, color="#D9DEE4", zorder=1) ys = sorted(ypos[v] for v in s if v in ypos) if ys: axm.plot([x, x], [ys[0], ys[-1]], color=INK, lw=1.8, zorder=2) axm.scatter([x] * len(ys), ys, s=40, color=INK, zorder=3) axm.set_yticks([]) axm.set_ylim(len(elems) - 0.5, -0.5) axm.set_xticks([]) for s in ("top", "right", "bottom"): axm.spines[s].set_visible(False) axs.barh(range(len(elems)), [deg[v] for v in elems], color=GRAY, height=0.6) axs.set_ylim(len(elems) - 0.5, -0.5) axs.invert_xaxis() axs.yaxis.tick_right() axs.set_yticks(range(len(elems)), [str(v) for v in elems], fontsize=8) axs.tick_params(axis="y", length=0, pad=4) axs.set_xlabel("total", fontsize=8) for s in ("top", "left"): axs.spines[s].set_visible(False) if title: axb.set_title(title) return fig, {"bars": axb, "matrix": axm, "sets": axs}
[docs] def plot_house_of_quality(relationship: pd.DataFrame, importance=None, correlation: pd.DataFrame | None = None, *, ax=None, symbols=None, title: str | None = None, label_size: float = 8): """House of quality diagram: relationship matrix, importance column, technical importance row and roof. Relationship scores are drawn with the usual symbols (9 = ●, 3 = ○, 1 = △ by default); the roof shows the correlation of every pair of parameters (``++``, ``+``, ``-``, ``--`` for values ≥ 0.5, > 0, < 0, ≤ -0.5). """ ax = get_ax(ax, figsize=(9, 7)) R = relationship.fillna(0) n, m = R.shape symbols = symbols or {9: "●", 5: "◉", 3: "○", 1: "△"} for i in range(n + 1): ax.plot([0, m], [i, i], color="#B8C0CA", lw=0.6) for k in range(m + 1): ax.plot([k, k], [0, n], color="#B8C0CA", lw=0.6) for i, cr in enumerate(R.index): for k, dp in enumerate(R.columns): v = R.loc[cr, dp] if v: sym = symbols.get(int(v), f"{v:g}") ax.text(k + 0.5, n - i - 0.5, sym, ha="center", va="center", fontsize=11, color=BRAND) ax.text(-0.15, n - i - 0.5, str(cr), ha="right", va="center", fontsize=label_size) if importance is not None: imp = pd.Series(importance, index=R.index) for i, cr in enumerate(R.index): ax.text(m + 0.4, n - i - 0.5, f"{imp[cr]:g}", ha="center", va="center", fontsize=label_size, color=PALETTE[1]) ax.text(m + 0.4, n + 0.2, "importance", rotation=90, ha="center", va="bottom", fontsize=label_size) tech = R.mul(imp, axis=0).sum() for k, dp in enumerate(R.columns): ax.text(k + 0.5, -0.45, f"{tech[dp]:g}", ha="center", va="center", fontsize=label_size, color=PALETTE[2]) ax.text(-0.15, -0.45, "technical importance", ha="right", va="center", fontsize=label_size, color=PALETTE[2]) for k, dp in enumerate(R.columns): ax.text(k + 0.5, n + 0.15, str(dp), rotation=90, ha="center", va="bottom", fontsize=label_size) top = n + 2.1 if correlation is not None: C = correlation.reindex(index=R.columns, columns=R.columns).fillna(0) for k in range(m): for l_ in range(k + 1, m): cx = (k + l_ + 1) / 2 cy = top + (l_ - k) / 2 diamond = [(cx, cy - 0.5), (cx + 0.5, cy), (cx, cy + 0.5), (cx - 0.5, cy)] ax.add_patch(Polygon(diamond, closed=True, facecolor="white", edgecolor="#B8C0CA", lw=0.5)) val = C.iloc[k, l_] if val: s = "++" if val >= 0.5 else "+" if val > 0 else "--" if val <= -0.5 else "-" ax.text(cx, cy, s, ha="center", va="center", fontsize=7, color=PALETTE[2] if val > 0 else PALETTE[1]) ax.set_ylim(-1, top + m / 2 + 0.6) else: ax.set_ylim(-1, top) ax.set_xlim(-6, m + 1) ax.set_aspect("equal") ax.axis("off") if title: ax.set_title(title) return ax
[docs] def plot_similarity_matrix(H: Hypergraph, *, ax=None, measure: str = "jaccard", transitive: bool = False, order: str = "hierarchical", labels: bool = True, title: str | None = None): """Heat map of the vertex similarity matrix in a seriated order.""" from ..seriation import hierarchical_order from ..similarity import vertex_similarity ax = get_ax(ax, figsize=(5.5, 5)) S = vertex_similarity(H, measure, transitive=transitive) idx = hierarchical_order(1 - S, metric="euclidean") if order == "hierarchical" else np.arange(H.n_nodes) im = ax.imshow(S[np.ix_(idx, idx)], cmap=BRAND_CMAP, vmin=0, vmax=1) if labels: lab = [str(H.nodes[i]) for i in idx] ax.set_xticks(range(len(idx)), lab, rotation=90, fontsize=7) ax.set_yticks(range(len(idx)), lab, fontsize=7) plt.colorbar(im, ax=ax, fraction=0.046, label="similarity") if title: ax.set_title(title) return ax