svgld-heatmap
LD heatmap (pairwise linkage disequilibrium)
Which markers are inherited together, and where do the blocks of strong linkage disequilibrium start and end?
How to read it
- Read each cell as one pair of markers: darker means stronger linkage disequilibrium (r² or |D′| near 1).
- In the triangle, follow a cell up its two diagonals to the markers it pairs; cells next to the marker row pair neighbours.
- Dark triangles along the top are blocks of markers inherited together; a light band between them marks where recombination broke the link.
- Callout 1: A block: neighbouring markers in strong LD.
- Callout 2: Cells far down pair distant markers.
- 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
# 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 plotly.express as px
import plotly.graph_objects as go
from plotly.colors import sample_colorscale
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 px.colors.qualitative.Plotly
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)
scale = [[0, SEQ[0]], [1, SEQ[-1]]]
fig = go.Figure()
if LAYOUT == "square":
z = M[1:, :-1]
text = [[cell_text(v) if (LABELS and k <= 16 and not np.isnan(v)) else "" for v in row] for row in z]
fig.add_heatmap(z=z, x=markers[:-1], y=markers[1:], colorscale=scale, zmin=0, zmax=1, text=text, texttemplate="%{text}", colorbar=dict(title=VALUE))
fig.update_yaxes(autorange="reversed")
else:
cx, cy, cv, ct = [], [], [], []
for j in range(k):
for i in range(j):
x0, y0, v = (i + j + 1) / 2, -(j - i) / 2, M[j, i] # Haploview diamond centre
path = f"M {x0} {y0 + 0.5} L {x0 + 0.5} {y0} L {x0} {y0 - 0.5} L {x0 - 0.5} {y0} Z"
fill = sample_colorscale(scale, [min(1, max(0, v))])[0] if not np.isnan(v) else "rgba(0,0,0,0)"
fig.add_shape(type="path", path=path, fillcolor=fill, line=dict(color="white", width=0.5))
if not np.isnan(v):
cx.append(x0); cy.append(y0); cv.append(v); ct.append(f"{markers[i]} – {markers[j]}: {v:.3f}")
fig.add_scatter(x=cx, y=cy, mode="markers+text" if (LABELS and k <= 16) else "markers", text=[cell_text(v) for v in cv] if (LABELS and k <= 16) else None,
hovertext=ct, hoverinfo="text", showlegend=False,
marker=dict(size=1, color=cv, colorscale=scale, cmin=0, cmax=1, showscale=True, colorbar=dict(title=VALUE)))
for m, name in enumerate(markers):
fig.add_annotation(x=m + 0.5, y=0.1, text=name, showarrow=False, textangle=-45, xanchor="left", yanchor="bottom")
fig.update_layout(xaxis=dict(range=[0, k], visible=False), yaxis=dict(range=[-k / 2, 1.5], scaleanchor="x", visible=False))
fig.show()Needs pandas, numpy, plotly · reads ld-heatmap-demo.csv · app theme from the optional codesplash helper
# LD heatmap (pairwise linkage disequilibrium) — Codesplash Chart Lab (recipe "ld-heatmap")
# controls: layout=triangle, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("ld-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["marker A"]] <- factor(df[["marker A"]])
df[["marker B"]] <- factor(df[["marker B"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
a_col <- "marker A"
b_col <- "marker B"
value_col <- "r²"
layout <- "triangle"; labels <- TRUE
ab <- cbind(as.character(df[[a_col]]), as.character(df[[b_col]]))
markers <- unique(c(t(ab))) # first appearance over A then B, row by row
markers <- markers[!is.na(markers)]
k <- length(markers)
d <- data.frame(a = ab[, 1], b = ab[, 2], v = suppressWarnings(as.numeric(df[[value_col]])), stringsAsFactors = FALSE)
d <- d[!is.na(d$a) & !is.na(d$b) & !is.na(d$v) & d$a != d$b, ]
d$i <- pmin(match(d$a, markers), match(d$b, markers)); d$j <- pmax(match(d$a, markers), match(d$b, markers))
d <- d[!duplicated(paste(d$i, d$j), fromLast = TRUE), ] # a pair listed twice keeps its last value
r2 <- round(d$v, 2)
d$lab <- ifelse(r2 %in% c(0, 1), as.character(r2), sub("^(-?)0\\.", "\\1.", sprintf("%.2f", d$v)))
show_text <- labels && k <= 16
fill_scale <- scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], limits = c(0, 1), oob = scales::squish, name = value_col)
if (layout == "square") {
d$col <- factor(markers[d$i], levels = markers[-k]); d$row <- factor(markers[d$j], levels = rev(markers[-1]))
p <- ggplot(d, aes(col, row, fill = v)) + geom_tile(colour = "white") + fill_scale +
labs(x = NULL, y = NULL) + coord_equal() + theme_cs + theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank())
if (show_text) p <- p + geom_text(aes(label = lab), size = 2.6)
} else {
# Haploview: each pair a diamond halfway between its markers, (j - i)/2 below them
d$cx <- (d$i + d$j - 1) / 2; d$cy <- -(d$j - d$i) / 2
poly <- do.call(rbind, lapply(seq_len(nrow(d)), function(r) data.frame(id = r, v = d$v[r], x = d$cx[r] + c(0, 0.5, 0, -0.5), y = d$cy[r] + c(0.5, 0, -0.5, 0))))
p <- ggplot(poly, aes(x, y, group = id, fill = v)) + geom_polygon(colour = "white", linewidth = 0.3) + fill_scale +
annotate("text", x = seq_len(k) - 0.5, y = 0.1, label = markers, angle = 45, hjust = 0, size = 2.6) +
coord_equal(xlim = c(0, k), ylim = c(-k / 2, 1.5), clip = "off") + labs(x = NULL, y = NULL) + theme_cs +
theme(axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank())
if (show_text) p <- p + geom_text(data = d, aes(cx, cy, label = lab), inherit.aes = FALSE, size = 2.4)
}
print(p)Needs ggplot2 · reads ld-heatmap-demo.csv · app theme from the optional codesplashr helper