Skip to content
svgsfs-bar

Site frequency spectrum

How many sites carry the derived allele once, twice, …, and does that match what a constant-size neutral population predicts?

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

How to read it

  1. Read each bar as the number of segregating sites whose derived allele is carried by that many of the n sequences.
  2. Compare the bars with the dashed neutral expectation θ_W / i, scaled to the same number of sites.
  3. Too many singletons (left bars above the line) is what growth or a sweep leaves; too many middle classes is what balancing selection or structure leaves.
  1. Callout 1: Singletons: one sequence carries the derived allele.
  2. Callout 2: Middle classes.
  3. Callout 3: The neutral expectation θ_W / i.

Watch out

  • Fold the spectrum when the ancestral allele is unknown; an unfolded spectrum with a wrong ancestral call puts sites at the far end.
  • Demography and selection shape the spectrum in similar ways; a departure is compatible with several histories, and Tajima's D summarises it in one number.

Defaults

Sequences (n)
0
Sequences sampled per site; 0 uses the largest count + 1. Set it for folded or pre-counted spectra.
Range 0 to 100,000, step 1
Fold the spectrum
Off
Combines counts i and n − i into the minor-allele class, for when the ancestral allele is unknown.
Neutral expectation
On
θ_W / i scaled to the observed number of segregating sites (folded: i and n − i combined).

Pinned in the code

  • Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
  • Classes are 1 … n − 1 (folded: 1 … ⌊n/2⌋); sites with count 0 or n are not segregating and are left out, as are missing, non-integer or out-of-range counts.
  • With the second role bound, each row is a class and its number of sites (a spectrum the method already counted).
  • Expectation: θ_W / i with θ_W = S / a₁, a₁ = Σ 1/i, so it sums to the observed S; folded classes add i and n − i, halved when i = n − i (Tajima 1989; Fu 1995).

Use with care

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

# Site frequency spectrum — Codesplash Chart Lab (recipe "sfs-bar")
# controls: n=0, folded=false, expected=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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("sfs-bar-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

COUNT = "derived"
SITES = None
N, FOLDED, EXPECTED = 0, False, True  # sequences (0 = largest count + 1), fold, neutral expectation
k = pd.to_numeric(df[COUNT], errors="coerce")
w = pd.to_numeric(df[SITES], errors="coerce") if SITES else pd.Series(1.0, index=df.index)  # sites per row (pre-counted spectrum) or 1
ok = k.notna() & ((k - k.round()).abs() <= 1e-9) & (k >= 0) & w.notna() & (w >= 0)
k, w = k[ok].round().astype(int), w[ok]
n = int(round(N)) if N > 0 else (int(k.max()) + 1 if len(k) else 0)
seg = (k > 0) & (k < n)  # counts 0 and n are not segregating
k, w = k[seg].to_numpy(), w[seg].to_numpy()
cls = np.minimum(k, n - k) if FOLDED else k
K = n // 2 if FOLDED else n - 1
obs = np.bincount(cls - 1, weights=w, minlength=K)[:K] if K > 0 else np.zeros(0)
S = obs.sum()
a1 = (1 / np.arange(1, n)).sum()  # Watterson's a1
i = np.arange(1, K + 1)
exp = (S / a1) * ((1 / i + 1 / (n - i)) / np.where(i == n - i, 2, 1) if FOLDED else 1 / i)  # θ_W / i, sums to S (Tajima 1989; Fu 1995)
XLABEL = "minor-allele count" if FOLDED else "derived-allele count"
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(i, obs, width=0.78, color=PALETTE[0], alpha=0.85, label=f"observed (S = {S:g})")
if EXPECTED and S > 0:
    ax.plot(i, exp, color=PALETTE[1], linestyle="--", marker="o", markersize=4, label=f"neutral expectation (θ_W = {S / a1:.4g})")
ax.set_xlabel(XLABEL)
ax.set_ylabel("sites")
ax.legend(frameon=False)
plt.show()

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