#!/usr/bin/env python3 """Plot a trait's values grouped by genotype class at one marker, as one SVG. This is the picture R/qtl's book uses to look at a QTL by hand (Fig 4.1): each animal is a point, x is its genotype call at the peak marker, y is its phenotype value. A class whose points sit apart from the others is what a mapping score is made of -- and a class with two points is a warning. Input is the JSON the peak-genotypes endpoint returns, with the trait's values beside it: {"marker": "UNC26663082", "chr": "16", "points": [{"individual": "TB001", "genotype": "B", "value": 3.4}, ...]} python3 plot-genotypes.py points.json -o genotypes.svg Standard library only; writes plain SVG (light/dark aware), like the other plotters here. """ import argparse, json, sys WIDTH, HEIGHT = 760, 420 MARGIN_LEFT, MARGIN_RIGHT = 70, 24 MARGIN_TOP, MARGIN_BOTTOM = 54, 62 # A deterministic jitter: two animals with one call would otherwise land on # top of each other, and a stack of points is a fact about the data (many # animals, one class), not noise to hide. def jitter(index, count): if count <= 1: return 0.0 step = 0.6 / max(count - 1, 1) return (index - (count - 1) / 2.0) * step def esc(text): return (str(text).replace("&", "&").replace("<", "<").replace(">", ">") .replace('"', """)) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("document", help="JSON: marker, optional chr, points[]") ap.add_argument("--trait", default=json.loads(open(sys.argv[1]).read()).get("trait", "trait")) ap.add_argument("--title", default=None) ap.add_argument("-o", "--out", default=None) arguments = ap.parse_args() document = json.load(open(arguments.document)) points = [p for p in document.get("points", []) if p.get("value") is not None] if not points: print("no points with a value", file=sys.stderr) return 1 marker = document.get("marker", "marker") chromosome = document.get("chr") title = arguments.title or f"{arguments.trait}: {marker}" + ( f" (chr {chromosome})" if chromosome else "") classes = sorted({str(p["genotype"]) for p in points}) values = [float(p["value"]) for p in points] low, high = min(values), max(values) if high == low: high = low + 1.0 span = high - low plot_width = WIDTH - MARGIN_LEFT - MARGIN_RIGHT plot_height = HEIGHT - MARGIN_TOP - MARGIN_BOTTOM def y_of(value): return MARGIN_TOP + plot_height * (1 - (value - low) / span) def x_of(class_index): return MARGIN_LEFT + plot_width * (class_index + 0.5) / len(classes) parts = [ f'', "", f'', f'{esc(title)}', f'' f'genotype at {esc(marker)} ({len(points)} animals with a value)', ] # Y grid and labels. for step in range(0, 5): value = low + span * step / 4.0 y = y_of(value) parts.append(f'') parts.append(f'{value:.2f}') parts.append(f'') # Points, class by class, with the class mean drawn through them. for index, genotype in enumerate(classes): members = [p for p in points if str(p["genotype"]) == genotype] centre = x_of(index) for order, point in enumerate(sorted(members, key=lambda p: float(p["value"]))): x = centre + jitter(order, len(members)) * plot_width / len(classes) parts.append(f'{esc(point.get("individual", ""))}: ' f'{float(point["value"]):.3f}') mean = sum(float(p["value"]) for p in members) / len(members) half = 0.32 * plot_width / len(classes) parts.append(f'') parts.append(f'{esc(genotype)} (n={len(members)})') parts.append(f'mean {mean:.2f}') parts.append("") out = arguments.out if out: open(out, "w").write("\n".join(parts)) print(f"wrote {out}", file=sys.stderr) else: print("\n".join(parts)) return 0 if __name__ == "__main__": raise SystemExit(main())