"""Shared-X gradient histograms, independent colored Y axes and normal fits. Reconstructed from a user image; default samples are synthetic, not paper data. Custom CSV uses columns group,value. Normal fits describe data; they do not establish normality. Independent Y scales do not permit direct height comparison. """ from pathlib import Path import argparse import csv import json import sys import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from matplotlib.colors import to_rgb from matplotlib.lines import Line2D from matplotlib.patches import Patch from matplotlib.ticker import MaxNLocator, MultipleLocator for base in (Path.cwd(), *Path.cwd().parents, *Path(__file__).resolve().parents): found = next((p for p in (base/'_utils', base/'original/resources/assets/shared-scripts') if (p/'vivid_config.py').is_file()), None) if found is not None: sys.path.insert(0, str(found)) break else: raise RuntimeError('Run Vivid bootstrap in the workspace before using this recipe.') from vivid_config import categorical_colors from plot_utils import setup_style def read_samples(path): groups = {} with Path(path).open(encoding='utf-8-sig', newline='') as stream: rows = csv.DictReader(stream) if not {'group', 'value'}.issubset(rows.fieldnames or []): raise ValueError('CSV requires group,value columns.') for row in rows: name = row['group'].strip() if not name: raise ValueError('Group labels cannot be empty.') groups.setdefault(name, []).append(float(row['value'])) return groups def plot_chart(groups, *, bins=14, xlabel='Residual', fit=True, ylimits=None, note=None, colors=None, xlim=None, ytick_step=None): """One to three groups of raw observations with a shared X scale. bins may be shared or a dict of group-specific equal-width bin edges. Each normal curve is mean/std(ddof=0) fitted to its own raw sample, scaled by sample count * bin width to approximate frequency on that group's axis. Optional ylimits supplies one (0, upper) pair per group without clipping. """ if not 1 <= len(groups) <= 3: raise ValueError('Use one to three groups to keep the independent axes readable.') arrays = {str(name): np.asarray(values, dtype=float) for name, values in groups.items()} if len(arrays) != len(groups) or any(not name.strip() for name in arrays): raise ValueError('Group labels must be distinct nonempty strings.') for name, values in arrays.items(): if values.ndim != 1 or len(values) < 2 or not np.isfinite(values).all(): raise ValueError(f'{name}: provide at least two finite raw observations.') if fit and values.std(ddof=0) <= 0: raise ValueError(f'{name}: zero variance; disable the normal fit.') combined = np.concatenate(list(arrays.values())) if isinstance(bins, dict) and set(bins) != set(arrays): raise ValueError('Group-specific bins must include every group exactly once.') bin_edges = {} for name, values in arrays.items(): edges = np.histogram_bin_edges(values if isinstance(bins,dict) else combined, bins=bins[name] if isinstance(bins,dict) else bins) widths = np.diff(edges) if (len(widths) < 2 or not np.isfinite(edges).all() or (widths <= 0).any() or not np.allclose(widths, widths[0]) or edges[0] > values.min() or edges[-1] < values.max()): raise ValueError('Each group needs equal-width bins covering all its observations.') bin_edges[name] = edges if ylimits is not None and len(ylimits) != len(arrays): raise ValueError('Supply one Y range for every group.') if ytick_step is not None and (not np.isfinite(ytick_step) or ytick_step <= 0): raise ValueError('Y tick step must be positive and finite.') setup_style() colors = categorical_colors() if colors is None else colors if len(colors) < len(arrays): raise ValueError('The selected palette needs at least one color per group.') plt.rcParams.update({'font.family': 'serif', 'font.serif': ['Times New Roman', 'DejaVu Serif'], 'font.weight': 'bold', 'axes.labelweight': 'bold', 'pdf.fonttype': 42, 'font.size': 11, 'axes.linewidth': 1.25}) fig, host = plt.subplots(figsize=(9.5, 7.2)) fig.subplots_adjust(left=.085, right=.86 if len(arrays) == 3 else .92, bottom=.12, top=.975) axes = [host] + [host.twinx() for _ in range(len(arrays)-1)] extent = (min(e[0] for e in bin_edges.values()), max(e[-1] for e in bin_edges.values())) if xlim is not None and (len(xlim)!=2 or not np.isfinite(xlim).all() or xlim[0]>extent[0] or xlim[1]