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?
How to read it
- Read each bar as the number of segregating sites whose derived allele is carried by that many of the n sequences.
- Compare the bars with the dashed neutral expectation θ_W / i, scaled to the same number of sites.
- 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.
- Callout 1: Singletons: one sequence carries the derived allele.
- Callout 2: Middle classes.
- 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
# 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 plotly.express as px
import plotly.graph_objects as go
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("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 = go.Figure()
fig.add_bar(x=i, y=obs, marker_color=PALETTE[0], opacity=0.85, name=f"observed (S = {S:g})")
if EXPECTED and S > 0:
fig.add_scatter(x=i, y=exp, mode="lines+markers", line=dict(color=PALETTE[1], dash="dash"), name=f"neutral expectation (θ_W = {S / a1:.4g})")
fig.update_layout(xaxis_title=XLABEL, yaxis_title="sites", bargap=0.22)
fig.show()Needs pandas, numpy, plotly · reads sfs-bar-demo.csv · app theme from the optional codesplash helper
# Site frequency spectrum — Codesplash Chart Lab (recipe "sfs-bar")
# controls: n=0, folded=false, expected=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("sfs-bar-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
count_col <- "derived"
sites_col <- NULL
n_seq <- 0; folded <- FALSE; show_expected <- TRUE # sequences (0 = largest + 1)
kk <- suppressWarnings(as.numeric(df[[count_col]]))
ww <- if (!is.null(sites_col)) suppressWarnings(as.numeric(df[[sites_col]])) else rep(1, nrow(df)) # sites per row or 1
ok <- !is.na(kk) & abs(kk - round(kk)) <= 1e-9 & kk >= 0 & !is.na(ww) & ww >= 0
kk <- round(kk[ok]); ww <- ww[ok]
n <- if (n_seq > 0) round(n_seq) else if (length(kk)) max(kk) + 1 else 0
seg <- kk > 0 & kk < n; kk <- kk[seg]; ww <- ww[seg] # counts 0 and n are not segregating
cls <- if (folded) pmin(kk, n - kk) else kk
K <- if (folded) n %/% 2 else n - 1
obs <- vapply(seq_len(K), function(j) sum(ww[cls == j]), numeric(1))
S <- sum(obs); a1 <- sum(1 / seq_len(n - 1)); i <- seq_len(K)
ex <- if (folded) (S / a1) * (1 / i + 1 / (n - i)) / ifelse(i == n - i, 2, 1) else (S / a1) / i # theta_W / i (Tajima 1989; Fu 1995)
d <- data.frame(k = i, observed = obs, expected = ex)
p <- ggplot(d, aes(k, observed)) + geom_col(fill = cs_cat[1], alpha = 0.85, width = 0.78)
if (show_expected && S > 0) p <- p + geom_line(aes(y = expected), colour = cs_cat[2], linetype = "dashed") + geom_point(aes(y = expected), colour = cs_cat[2], size = 1.6)
p <- p + labs(x = if (folded) "minor-allele count" else "derived-allele count", y = "sites", subtitle = sprintf("S = %g, theta_W = %.4g", S, S / a1)) + theme_cs
print(p)Needs ggplot2 · reads sfs-bar-demo.csv · app theme from the optional codesplashr helper