Skip to content
svgmanhattan

Manhattan plot (association scan)

Where along the genome do markers show association with the trait, and does any pass the genome-wide threshold?

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

How to read it

  1. Read each point as one marker: the higher it sits, the smaller its p-value (−log₁₀ p).
  2. 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.
  3. Use the suggestive line for markers worth following up, and the labels to name the strongest hits.
  1. Callout 1: A peak crossing the genome-wide line.
  2. Callout 2: The genome-wide line (5 × 10⁻⁸).
  3. 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