Skip to content
svgld-heatmap

LD heatmap (pairwise linkage disequilibrium)

Which markers are inherited together, and where do the blocks of strong linkage disequilibrium start and end?

Demo data · seed 20261101 · 66 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each cell as one pair of markers: darker means stronger linkage disequilibrium (r² or |D′| near 1).
  2. In the triangle, follow a cell up its two diagonals to the markers it pairs; cells next to the marker row pair neighbours.
  3. Dark triangles along the top are blocks of markers inherited together; a light band between them marks where recombination broke the link.
  1. Callout 1: A block: neighbouring markers in strong LD.
  2. Callout 2: Cells far down pair distant markers.
  3. Callout 3: Marker names run along the top.

Watch out

  • |D′| = 1 is common with rare alleles even without real linkage; read r² to judge how well one marker tags another.
  • Markers are evenly spaced here, whatever their base-pair distances; a block may span very different physical lengths.

Defaults

Layout
Triangle (Haploview)
Triangle: rotated cells under the marker row, as in Haploview. Square: a lower-triangular matrix.
Also: Square (lower triangle)
Values in cells
On
Prints each pair's value (as .85) when there are 16 markers or fewer.

Pinned in the code

  • Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
  • Markers keep the order in which the pairs first name them (marker A, then marker B, row by row), which is the engine's marker order.
  • Shade runs from 0 (light) to 1 (dark) on the theme's sequential ramp; values outside 0–1 are clamped for colour. Pairs with no row are drawn as empty outlines.
  • In the triangle layout the cell for markers i and j sits halfway between them, (j − i) half-cells below the marker row (Barrett et al. 2005).

Use with care

Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result.

# LD heatmap (pairwise linkage disequilibrium) — Codesplash Chart Lab (recipe "ld-heatmap")
# controls: layout=triangle, labels=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.collections import PolyCollection

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("ld-heatmap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
A = "marker A"
B = "marker B"
VALUE = "r²"
LAYOUT, LABELS = "triangle", True
# marker order: first appearance over A then B, row by row
markers = list(dict.fromkeys(str(v) for pair in zip(df[A], df[B]) for v in pair if pd.notna(v)))
idx = {m: i for i, m in enumerate(markers)}
k = len(markers)
M = np.full((k, k), np.nan)  # M[j, i] = value of the pair (i < j); a pair listed twice keeps its last value
for a, b, v in zip(df[A], df[B], pd.to_numeric(df[VALUE], errors="coerce")):
    if pd.isna(a) or pd.isna(b) or pd.isna(v) or str(a) == str(b):
        continue
    i, j = sorted((idx[str(a)], idx[str(b)]))
    M[j, i] = v
def cell_text(v):
    r = round(float(v), 2)
    return str(int(r)) if r in (0, 1) else f"{r:.2f}".replace("0.", ".", 1)
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, ax = plt.subplots(figsize=(7.5, 6))
if LAYOUT == "square":
    im = ax.imshow(M[1:, :-1], cmap=cmap, vmin=0, vmax=1)  # rows: markers 2..k, columns: 1..k−1
    ax.set_xticks(range(k - 1), markers[:-1], rotation=45, ha="right")
    ax.set_yticks(range(k - 1), markers[1:])
    for j in range(1, k):
        for i in range(j):
            if LABELS and k <= 16 and not np.isnan(M[j, i]):
                ax.text(i, j - 1, cell_text(M[j, i]), ha="center", va="center", fontsize=7, color="white" if M[j, i] > 0.55 else "black")
else:
    polys, vals, centres = [], [], []
    for j in range(k):
        for i in range(j):
            cx, cy = (i + j + 1) / 2, -(j - i) / 2  # Haploview: halfway between the markers, (j − i)/2 below them
            polys.append([(cx, cy + 0.5), (cx + 0.5, cy), (cx, cy - 0.5), (cx - 0.5, cy)])
            vals.append(M[j, i])
            centres.append((cx, cy))
    im = PolyCollection(polys, array=np.ma.masked_invalid(vals), cmap=cmap, edgecolors="white", linewidths=0.5)
    im.set_clim(0, 1)
    ax.add_collection(im)
    for m, name in enumerate(markers):
        ax.text(m + 0.5, 0.1, name, rotation=45, ha="left", va="bottom", fontsize=8)
    if LABELS and k <= 16:
        for (cx, cy), v in zip(centres, vals):
            if not np.isnan(v):
                ax.text(cx, cy, cell_text(v), ha="center", va="center", fontsize=7, color="white" if v > 0.55 else "black")
    ax.set_xlim(0, k)
    ax.set_ylim(-k / 2, 1.5)
    ax.set_aspect("equal")
    ax.axis("off")
fig.colorbar(im, ax=ax, shrink=0.6, label=VALUE)
plt.show()

Needs pandas, numpy, matplotlib · reads ld-heatmap-demo.csv · app theme from the optional codesplash helper