svgmanhattan
Manhattan plot (association scan)
Where along the genome do markers show association with the trait, and does any pass the genome-wide threshold?
How to read it
- Read each point as one marker: the higher it sits, the smaller its p-value (−log₁₀ p).
- Look for towers that cross the genome-wide line; a real signal usually shows as a peak of neighbouring markers in LD, not one lone point.
- Use the suggestive line for markers worth following up, and the labels to name the strongest hits.
- Callout 1: A peak crossing the genome-wide line.
- Callout 2: The genome-wide line (5 × 10⁻⁸).
- Callout 3: Chromosomes side by side in alternating shades.
Watch out
- Check the QQ plot and λ_GC first: inflation from population structure lifts every chromosome and makes false towers.
- A peak marks a region associated with the trait; it is compatible with several causal variants nearby, and the top marker need not be one of them.
Defaults
- Genome-wide line
- 5e-8
- p below this line is genome-wide significant; 5 × 10⁻⁸ is the usual line for a whole genome.
- Range 1e-300 to 0.5, step 1e-8
- Suggestive line
- 0.00001
- A second, looser line to flag markers worth following up (0 hides it).
- Range 0 to 0.5, step 0.00001
- Label top markers
- 3
- Labels this many markers with the smallest p-values (0 labels none).
- Range 0 to 20, step 1
Pinned in the code
- Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
- y = −log₁₀ p. Rows with a missing position or a p outside (0, 1] are left out (a p of exactly 0 has no −log₁₀).
- With more than one chromosome, they are placed in the order 1–22, X, Y, XY, MT (others A→Z), each starting where the last ended plus a gap of 0.5% of the summed spans; within a chromosome x = position − its first position.
- With one chromosome (or none) x is the position as given; without base-pair positions, marker order works as the position.
Use with care
Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result. Positions are only meaningful when they are base pairs; with marker order the spacing is even, whatever the real distances.
# Manhattan plot (association scan) — Codesplash Chart Lab (recipe "manhattan")
# controls: gw=5e-8, suggestive=0.00001, top=3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re
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("manhattan-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["chromosome"] = pd.Categorical(df["chromosome"].astype("string"), categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22"])
_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")
POS = "position (bp)"
P = "p"
CHROM = "chromosome"
LABEL = "marker"
GW, SUGGESTIVE, TOP = 5e-8, 0.00001, 3 # lines (0 = none) and top markers to label
SPECIAL = {"X": 1000, "Y": 1001, "XY": 1002, "M": 1003, "MT": 1003}
def chrom_key(name):
s = re.sub(r"^chr", "", str(name).strip(), flags=re.I)
u = s.upper()
return (int(s), "", str(name)) if s.isdigit() else (SPECIAL[u], "", str(name)) if u in SPECIAL else (2000, u, str(name))
d = pd.DataFrame({"pos": pd.to_numeric(df[POS], errors="coerce"), "p": pd.to_numeric(df[P], errors="coerce")})
d["chrom"] = df[CHROM].astype("string").fillna("unknown").astype(str) if CHROM else ""
d["label"] = df[LABEL].astype("string") if LABEL else None
d = d[d["pos"].notna() & (d["p"] > 0) & (d["p"] <= 1)].copy() # a p of 0 has no −log10
order = sorted(d["chrom"].unique(), key=chrom_key) # 1–22, X, Y, XY, MT, then others
span = d.groupby("chrom")["pos"].agg(["min", "max"]).loc[order]
multi = len(order) > 1
if multi:
width = span["max"] - span["min"]
gap = width.sum() * 0.005 if width.sum() > 0 else 1 # 0.5% of the summed spans between chromosomes
span["offset"] = np.concatenate([[0], np.cumsum((width + gap).to_numpy())[:-1]])
d["x"] = d["chrom"].map(span["offset"]) + d["pos"] - d["chrom"].map(span["min"])
centres = span["offset"] + width / 2
else:
d["x"] = d["pos"]
d["y"] = -np.log10(d["p"])
d["band"] = d["chrom"].map({ch: i % 2 for i, ch in enumerate(order)})
top = d.sort_values("p", kind="stable").head(TOP)
def top_label(r):
if LABEL and pd.notna(r["label"]):
return str(r["label"])
return f"{r['chrom']}:{r['pos']:g}" if multi else f"{r['pos']:g}"
fig, ax = plt.subplots(figsize=(10, 4.5))
for b, alpha in ((0, 1.0), (1, 0.5)): # alternating shades by chromosome
s = d[d["band"] == b]
ax.scatter(s["x"], s["y"], s=6, color=PALETTE[0], alpha=alpha, linewidths=0)
if 0 < SUGGESTIVE < 1:
ax.axhline(-np.log10(SUGGESTIVE), color=REF, linestyle="--", linewidth=1, label=f"suggestive {SUGGESTIVE:g}")
if 0 < GW < 1:
ax.axhline(-np.log10(GW), color=PALETTE[3], linewidth=1.2, label=f"genome-wide {GW:g}")
for _, r in top.iterrows():
ax.scatter([r["x"]], [r["y"]], s=40, facecolors="none", edgecolors="black", linewidths=0.8)
ax.annotate(top_label(r), (r["x"], r["y"]), xytext=(4, 5), textcoords="offset points", fontsize=8)
if multi:
ax.set_xticks(centres.to_numpy(), [re.sub(r"^chr", "", str(ch), flags=re.I) for ch in order], fontsize=7)
ax.set_xlabel("chromosome")
else:
ax.set_xlabel(POS)
lines = [-np.log10(t) for t in (GW, SUGGESTIVE) if 0 < t < 1]
ax.set_ylim(0, max([d["y"].max() if len(d) else 0, *lines, 1]) * 1.08)
ax.set_ylabel("−log₁₀ p")
if lines:
ax.legend(frameon=False, loc="upper right")
plt.show()Needs pandas, numpy, matplotlib, re · reads manhattan-demo.csv · app theme from the optional codesplash helper
# Manhattan plot (association scan) — Codesplash Chart Lab (recipe "manhattan")
# controls: gw=5e-8, suggestive=0.00001, top=3
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import re
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("manhattan-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["chromosome"] = pd.Categorical(df["chromosome"].astype("string"), categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22"])
_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")
POS = "position (bp)"
P = "p"
CHROM = "chromosome"
LABEL = "marker"
GW, SUGGESTIVE, TOP = 5e-8, 0.00001, 3 # lines (0 = none) and top markers to label
SPECIAL = {"X": 1000, "Y": 1001, "XY": 1002, "M": 1003, "MT": 1003}
def chrom_key(name):
s = re.sub(r"^chr", "", str(name).strip(), flags=re.I)
u = s.upper()
return (int(s), "", str(name)) if s.isdigit() else (SPECIAL[u], "", str(name)) if u in SPECIAL else (2000, u, str(name))
d = pd.DataFrame({"pos": pd.to_numeric(df[POS], errors="coerce"), "p": pd.to_numeric(df[P], errors="coerce")})
d["chrom"] = df[CHROM].astype("string").fillna("unknown").astype(str) if CHROM else ""
d["label"] = df[LABEL].astype("string") if LABEL else None
d = d[d["pos"].notna() & (d["p"] > 0) & (d["p"] <= 1)].copy() # a p of 0 has no −log10
order = sorted(d["chrom"].unique(), key=chrom_key) # 1–22, X, Y, XY, MT, then others
span = d.groupby("chrom")["pos"].agg(["min", "max"]).loc[order]
multi = len(order) > 1
if multi:
width = span["max"] - span["min"]
gap = width.sum() * 0.005 if width.sum() > 0 else 1 # 0.5% of the summed spans between chromosomes
span["offset"] = np.concatenate([[0], np.cumsum((width + gap).to_numpy())[:-1]])
d["x"] = d["chrom"].map(span["offset"]) + d["pos"] - d["chrom"].map(span["min"])
centres = span["offset"] + width / 2
else:
d["x"] = d["pos"]
d["y"] = -np.log10(d["p"])
d["band"] = d["chrom"].map({ch: i % 2 for i, ch in enumerate(order)})
top = d.sort_values("p", kind="stable").head(TOP)
def top_label(r):
if LABEL and pd.notna(r["label"]):
return str(r["label"])
return f"{r['chrom']}:{r['pos']:g}" if multi else f"{r['pos']:g}"
hover = (d["label"].astype(str) + " · " if LABEL else "") + d["chrom"].astype(str) + " " + d["pos"].map("{:g}".format) + " · p = " + d["p"].map("{:.3g}".format)
fig = go.Figure()
for b, alpha in ((0, 1.0), (1, 0.5)): # alternating shades by chromosome
m = (d["band"] == b).to_numpy()
fig.add_scattergl(x=d["x"][m], y=d["y"][m], mode="markers", marker=dict(size=4, color=PALETTE[0], opacity=alpha), hovertext=hover[m], hoverinfo="text", showlegend=False)
if 0 < SUGGESTIVE < 1:
fig.add_hline(y=-np.log10(SUGGESTIVE), line_dash="dash", line_color=REF, annotation_text=f"suggestive {SUGGESTIVE:g}")
if 0 < GW < 1:
fig.add_hline(y=-np.log10(GW), line_color=PALETTE[3], annotation_text=f"genome-wide {GW:g}")
for _, r in top.iterrows():
fig.add_annotation(x=r["x"], y=r["y"], text=top_label(r), showarrow=True, arrowhead=0, ax=20, ay=-20)
if multi:
fig.update_xaxes(tickvals=centres.to_numpy(), ticktext=[re.sub(r"^chr", "", str(ch), flags=re.I) for ch in order], title="chromosome")
else:
fig.update_xaxes(title=POS)
fig.update_yaxes(title="−log₁₀ p", rangemode="tozero")
fig.show()Needs pandas, numpy, plotly, re · reads manhattan-demo.csv · app theme from the optional codesplash helper
# Manhattan plot (association scan) — Codesplash Chart Lab (recipe "manhattan")
# controls: gw=5e-8, suggestive=0.00001, top=3
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("manhattan-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["chromosome"]] <- factor(df[["chromosome"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22"))
df[["marker"]] <- factor(df[["marker"]])
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
pos_col <- "position (bp)"
p_col <- "p"
chrom_col <- "chromosome"
label_col <- "marker"
gw <- 5e-8; suggestive <- 0.00001; top_n <- 3 # lines (0 = none), top markers to label
d <- data.frame(pos = suppressWarnings(as.numeric(df[[pos_col]])), p = suppressWarnings(as.numeric(df[[p_col]])))
d$chrom <- if (!is.null(chrom_col)) ifelse(is.na(df[[chrom_col]]), "unknown", as.character(df[[chrom_col]])) else ""
d$label <- if (!is.null(label_col)) as.character(df[[label_col]]) else NA_character_
d <- d[!is.na(d$pos) & !is.na(d$p) & d$p > 0 & d$p <= 1, ] # a p of 0 has no -log10
ch <- unique(d$chrom)
s <- sub("^chr", "", trimws(ch), ignore.case = TRUE); u <- toupper(s)
special <- c(X = 1000, Y = 1001, XY = 1002, M = 1003, MT = 1003)
key1 <- ifelse(grepl("^[0-9]+$", s), suppressWarnings(as.numeric(s)), ifelse(u %in% names(special), special[u], 2000))
key2 <- ifelse(key1 < 2000, "", u)
ch <- ch[order(key1, key2, ch)] # 1-22, X, Y, XY, MT, then others
lo <- tapply(d$pos, d$chrom, min)[ch]; hi <- tapply(d$pos, d$chrom, max)[ch]
multi <- length(ch) > 1
if (multi) {
gap <- if (sum(hi - lo) > 0) sum(hi - lo) * 0.005 else 1 # 0.5% of the summed spans between chromosomes
off <- c(0, cumsum(hi - lo + gap)[-length(ch)]); names(off) <- ch
d$x <- off[d$chrom] + d$pos - lo[d$chrom]
} else d$x <- d$pos
d$y <- -log10(d$p)
d$band <- factor((match(d$chrom, ch) - 1) %% 2, levels = c(0, 1))
top <- head(d[order(d$p), ], top_n)
top$lab <- ifelse(is.na(top$label), if (multi) paste0(top$chrom, ":", top$pos) else as.character(top$pos), top$label)
p <- ggplot(d, aes(x, y, colour = band)) + geom_point(size = 0.8) +
scale_colour_manual(values = c("0" = cs_cat[1], "1" = grDevices::adjustcolor(cs_cat[1], alpha.f = 0.5)), guide = "none")
if (suggestive > 0 && suggestive < 1) p <- p + geom_hline(yintercept = -log10(suggestive), colour = ref_col, linetype = "dashed")
if (gw > 0 && gw < 1) p <- p + geom_hline(yintercept = -log10(gw), colour = cs_cat[4])
if (nrow(top)) p <- p + geom_point(data = top, aes(x, y), inherit.aes = FALSE, shape = 1, size = 2.4) +
geom_text(data = top, aes(x, y, label = lab), inherit.aes = FALSE, vjust = -0.8, hjust = 0, size = 2.6)
p <- p + (if (multi) scale_x_continuous(breaks = off + (hi - lo) / 2, labels = sub("^chr", "", ch, ignore.case = TRUE)) else scale_x_continuous()) +
labs(x = if (multi) "chromosome" else pos_col, y = "-log10 p") + theme_cs + theme(panel.grid.major.x = element_blank())
print(p)Needs ggplot2 · reads manhattan-demo.csv · app theme from the optional codesplashr helper