#!/usr/bin/env python3 """Scatter plot of two compared traits, as one SVG panel. Input is the JSON response of POST /compute/compare (saved as-is): the paired values, the individual names, and the r/p/n they came with. The line is the ordinary least-squares line implied by r and the two means -- nothing is refitted here, and nothing is invented beyond what the reply carries. python3 plot-compare.py compare.json -o compare.svg --trait "1427571_at vs 1427641_at" Standard library only; writes plain SVG (light/dark aware). """ import argparse import json import sys W, H = 760, 520 L, R, T, B = 64, 150, 78, 64 def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("result", help="saved /compute/compare response (JSON)") ap.add_argument("-o", "--out", default="compare.svg") ap.add_argument("--trait", default="", help="label for the title") ap.add_argument("--title", default=None) a = ap.parse_args() doc = json.load(open(a.result)) data = doc.get("data") if isinstance(doc.get("data"), dict) else doc pairs = data.get("pairs") or [] if len(pairs) < 2: sys.exit(f"{a.result}: no `pairs` -- post a /compute/compare reply") r_value = data.get("r") p_value = data.get("p") n = data.get("n") or len(pairs) first = (data.get("a") or {}) second = (data.get("b") or {}) xs = [float(row[1]) for row in pairs] ys = [float(row[2]) for row in pairs] xmin, xmax = min(xs), max(xs) ymin, ymax = min(ys), max(ys) pad_x = (xmax - xmin) * 0.06 or 0.5 pad_y = (ymax - ymin) * 0.06 or 0.5 xmin, xmax = xmin - pad_x, xmax + pad_x ymin, ymax = ymin - pad_y, ymax + pad_y pw, ph = W - L - R, H - T - B def X(v): return L + (v - xmin) / (xmax - xmin) * pw def Y(v): return T + ph - (v - ymin) / (ymax - ymin) * ph label = a.trait or (f"{first.get('trait_name', 'a')} vs {second.get('trait_name', 'b')}") title = a.title or f"{label}: scatter" method = data.get("method") or "pearson" sub = (f"{method} r = {r_value:+.4f}" if isinstance(r_value, (int, float)) else f"{method} r = ?") if isinstance(p_value, (int, float)): sub += f", p = {p_value:.3g}" sub += f", n = {n}" if data.get("only_one_side"): sub += f" ยท {data['only_one_side']} individual(s) had a value for only one trait" desc = (f"Scatter of {first.get('trait_name', 'a')} ({first.get('dataset', '')}) against " f"{second.get('trait_name', 'b')} ({second.get('dataset', '')}) over {n} individuals, " f"{method} r {r_value}.") s = [f''' {title} {desc} {title} {sub}'''] for step in range(5): value = ymin + (ymax - ymin) * step / 4 y = Y(value) s.append(f'') s.append(f'{value:.3g}') for step in range(5): value = xmin + (xmax - xmin) * step / 4 x = X(value) s.append(f'{value:.3g}') # Least-squares line implied by r and the two standard deviations. if isinstance(r_value, (int, float)) and n > 2: mean_x = sum(xs) / n mean_y = sum(ys) / n var_x = sum((v - mean_x) ** 2 for v in xs) / (n - 1) var_y = sum((v - mean_y) ** 2 for v in ys) / (n - 1) if var_x > 0 and var_y > 0: slope = r_value * (var_y / var_x) ** 0.5 y_at = lambda v: mean_y + slope * (v - mean_x) s.append(f'') for row in pairs: name, xv, yv = row[0], float(row[1]), float(row[2]) s.append(f'{name}: {xv:.4g} vs {yv:.4g}') s.append(f'' f'{second.get("trait_name", "b")}') s.append(f'' f'{first.get("trait_name", "a")}') s.append(f'r = {r_value:+.4f}' if isinstance(r_value, (int, float)) else "") s.append(f'n = {n}') s.append(f'dashed: OLS') s.append(f'from r and the means') s.append("") open(a.out, "w").write("\n".join(s) + "\n") print(f"{a.out}: {n} points, r {r_value}") if __name__ == "__main__": main()