多Y轴渐变直方图与正态拟合
来源与调用 · 完整代码
1 """Shared-X gradient histograms, independent colored Y axes and normal fits.
2 Reconstructed from a user image; default samples are synthetic, not paper data.
3 Custom CSV uses columns group,value. Normal fits describe data; they do not
4 establish normality. Independent Y scales do not permit direct height comparison.
5 """
6 from pathlib import Path
7 import argparse
8 import csv
9 import json
10 import sys
11 import numpy as np
12 import matplotlib
13 matplotlib.use('Agg')
14 import matplotlib.pyplot as plt
15 from matplotlib.collections import PolyCollection
16 from matplotlib.colors import to_rgb
17 from matplotlib.lines import Line2D
18 from matplotlib.patches import Patch
19 from matplotlib.ticker import MaxNLocator, MultipleLocator
20
21 for base in (Path.cwd(), *Path.cwd().parents, *Path(__file__).resolve().parents):
22 found = next((p for p in (base/'_utils', base/'original/resources/assets/shared-scripts')
23 if (p/'vivid_config.py').is_file()), None)
24 if found is not None:
25 sys.path.insert(0, str(found))
26 break
27 else:
28 raise RuntimeError('Run Vivid bootstrap in the workspace before using this recipe.')
29 from vivid_config import categorical_colors
30 from plot_utils import setup_style
31
32
33 def read_samples(path):
34 groups = {}
35 with Path(path).open(encoding='utf-8-sig', newline='') as stream:
36 rows = csv.DictReader(stream)
37 if not {'group', 'value'}.issubset(rows.fieldnames or []):
38 raise ValueError('CSV requires group,value columns.')
39 for row in rows:
40 name = row['group'].strip()
41 if not name:
42 raise ValueError('Group labels cannot be empty.')
43 groups.setdefault(name, []).append(float(row['value']))
44 return groups
45
46
47 def plot_chart(groups, *, bins=14, xlabel='Residual', fit=True, ylimits=None,
48 note=None, colors=None, xlim=None, ytick_step=None):
49 """One to three groups of raw observations with a shared X scale.
50
51 bins may be shared or a dict of group-specific equal-width bin edges.
52
53 Each normal curve is mean/std(ddof=0) fitted to its own raw sample, scaled
54 by sample count * bin width to approximate frequency on that group's axis.
55 Optional ylimits supplies one (0, upper) pair per group without clipping.
56 """
57 if not 1 <= len(groups) <= 3:
58 raise ValueError('Use one to three groups to keep the independent axes readable.')
59 arrays = {str(name): np.asarray(values, dtype=float) for name, values in groups.items()}
60 if len(arrays) != len(groups) or any(not name.strip() for name in arrays):
61 raise ValueError('Group labels must be distinct nonempty strings.')
62 for name, values in arrays.items():
63 if values.ndim != 1 or len(values) < 2 or not np.isfinite(values).all():
64 raise ValueError(f'{name}: provide at least two finite raw observations.')
65 if fit and values.std(ddof=0) <= 0:
66 raise ValueError(f'{name}: zero variance; disable the normal fit.')
67 combined = np.concatenate(list(arrays.values()))
68 if isinstance(bins, dict) and set(bins) != set(arrays):
69 raise ValueError('Group-specific bins must include every group exactly once.')
70 bin_edges = {}
71 for name, values in arrays.items():
72 edges = np.histogram_bin_edges(values if isinstance(bins,dict) else combined,
73 bins=bins[name] if isinstance(bins,dict) else bins)
74 widths = np.diff(edges)
75 if (len(widths) < 2 or not np.isfinite(edges).all() or (widths <= 0).any()
76 or not np.allclose(widths, widths[0])
77 or edges[0] > values.min() or edges[-1] < values.max()):
78 raise ValueError('Each group needs equal-width bins covering all its observations.')
79 bin_edges[name] = edges
80 if ylimits is not None and len(ylimits) != len(arrays):
81 raise ValueError('Supply one Y range for every group.')
82 if ytick_step is not None and (not np.isfinite(ytick_step) or ytick_step <= 0):
83 raise ValueError('Y tick step must be positive and finite.')
84
85 setup_style()
86 colors = categorical_colors() if colors is None else colors
87 if len(colors) < len(arrays):
88 raise ValueError('The selected palette needs at least one color per group.')
89 plt.rcParams.update({'font.family': 'serif', 'font.serif': ['Times New Roman', 'DejaVu Serif'],
90 'font.weight': 'bold', 'axes.labelweight': 'bold',
91 'pdf.fonttype': 42, 'font.size': 11, 'axes.linewidth': 1.25})
92 fig, host = plt.subplots(figsize=(9.5, 7.2))
93 fig.subplots_adjust(left=.085, right=.86 if len(arrays) == 3 else .92,
94 bottom=.12, top=.975)
95 axes = [host] + [host.twinx() for _ in range(len(arrays)-1)]
96 extent = (min(e[0] for e in bin_edges.values()), max(e[-1] for e in bin_edges.values()))
97 if xlim is not None and (len(xlim)!=2 or not np.isfinite(xlim).all()
98 or xlim[0]>extent[0] or xlim[1]<extent[1]):
99 raise ValueError('X range must cover all histogram bins.')
100 host.set_xlim(*(extent if xlim is None else xlim))
101 host.set_xlabel(xlabel, fontsize=15)
102 host.spines['top'].set_visible(True)
103 host.tick_params(axis='x', top=True, direction='in', width=1.25, length=6)
104 # All data layers live on the host with each group's own data transform.
105 # This keeps every dashed fit above all translucent bars across twin axes.
106 host.set_zorder(10)
107 for ax in axes:
108 ax.patch.set_visible(False)
109 ax.grid(False)
110 legend_bars, legend_fits, stats = [], [], []
111 for i, ((name, values), ax) in enumerate(zip(arrays.items(), axes)):
112 color = colors[i]
113 edges = bin_edges[name]
114 widths = np.diff(edges)
115 counts, _ = np.histogram(values, bins=edges)
116 mu, sigma = float(values.mean()), float(values.std(ddof=0))
117 xfit = np.linspace(*host.get_xlim(), 700)
118 yfit = (len(values)*widths[0]/(sigma*np.sqrt(2*np.pi))
119 * np.exp(-.5*((xfit-mu)/sigma)**2)) if fit else np.zeros_like(xfit)
120 peak = max(float(counts.max()), float(yfit.max()), 1.)
121 ylim = (0., peak*1.28) if ylimits is None else tuple(ylimits[i])
122 if len(ylim) != 2 or not np.isfinite(ylim).all() or ylim[0] != 0 or ylim[1] < peak:
123 raise ValueError('Y ranges must start at zero and cover all counts and fitted peaks.')
124 ax.set_ylim(*ylim)
125 side = 'left' if i == 0 else 'right'
126 if i:
127 ax.spines['left'].set_visible(False)
128 ax.spines['top'].set_visible(False)
129 ax.spines['bottom'].set_visible(False)
130 ax.spines['right'].set_position(('axes', 1.+.12*(i-1)))
131 else:
132 ax.spines['right'].set_visible(False)
133 ax.spines[side].set_color(color)
134 ax.spines[side].set_visible(True)
135 ax.tick_params(axis='y', colors=color, direction='in', width=1.3, length=6)
136 ax.yaxis.set_major_locator(MaxNLocator(nbins=6, integer=True) if ytick_step is None
137 else MultipleLocator(ytick_step))
138 # Reference layout: one black frequency label; group/axis mapping is
139 # carried by colored ticks and the matching legend, not repeated titles.
140 ax.set_ylabel('Frequency' if i == 0 else '', color='black', fontsize=15, labelpad=6)
141
142 # True alpha gradient: transparent foot to colored cap, not an opaque
143 # white rectangle. Earlier groups remain visible through overlaps.
144 vertices, facecolors = [], []
145 rgb = to_rgb(color)
146 for left, width, height in zip(edges[:-1], widths, counts):
147 if height == 0:
148 continue
149 levels = np.linspace(0., float(height), 65)
150 for k, (low, high) in enumerate(zip(levels[:-1], levels[1:])):
151 x0, x1 = left+.11*width, left+.89*width
152 vertices.append([(x0,low),(x1,low),(x1,high),(x0,high)])
153 facecolors.append((*rgb, .02+.76*((k+.5)/64)**.85))
154 host.add_collection(PolyCollection(vertices, facecolors=facecolors,
155 edgecolors='none', antialiased=False,
156 transform=ax.transData, zorder=2+({0:.1,1:0.,2:.2}[i])), autolim=False)
157 legend_bars.append(Patch(facecolor=color, alpha=.75, edgecolor='none',
158 label=name))
159 if fit:
160 host.plot(xfit, yfit, color=color, ls='--', lw=2.2,
161 transform=ax.transData, zorder=5)
162 legend_fits.append(Line2D([],[],color=color,ls='--',lw=2.2,
163 label=fr'{name} fit ($\mu={mu:.1f},\ \sigma={sigma:.1f}$)'))
164 stats.append(dict(group=name,n=len(values),mean=mu,std_mle=sigma,
165 counts=counts.tolist(),bin_edges=edges.tolist(),
166 color=color,ylim=list(ylim),fit='normal_mle' if fit else None))
167 host.legend(handles=legend_bars[::-1]+legend_fits[::-1],loc='upper left',fontsize=8.6,
168 handlelength=2.2,labelspacing=.25,borderpad=.4,
169 frameon=True,facecolor='white',edgecolor='#aaaaaa',framealpha=.94)
170 if note:
171 fig.text(.085,.025,note,fontsize=8,color='#444444')
172 return fig, stats
173
174
175 def main():
176 parser = argparse.ArgumentParser(description=__doc__)
177 parser.add_argument('--data',type=Path,help='Long CSV: group,value')
178 parser.add_argument('--bins',type=int,default=None)
179 parser.add_argument('--no-fit',action='store_true')
180 parser.add_argument('--reference-colors',action='store_true',help='Explicit screenshot color reproduction; otherwise use the project palette')
181 parser.add_argument('--xlabel',default='Residual')
182 parser.add_argument('--output',type=Path,default=Path('figures/fig_multi_y_gradient_hist'))
183 args = parser.parse_args()
184 if args.data:
185 groups, note = read_samples(args.data), None
186 else:
187 groups = {}
188 # Controlled synthetic samples match the reference's approximate widths
189 # and locations; neither counts nor samples were recovered from the paper.
190 for name,n,mu,sigma,seed in [('Group A',90,3.1,14.3,17),
191 ('Group B',105,-6.5,23.4,53),
192 ('Group C',100,2.5,10.,11)]:
193 sample = np.random.default_rng(seed).normal(size=n)
194 groups[name] = (sample-sample.mean())/sample.std()*sigma+mu
195 note = 'Synthetic reconstruction; independent colored Y scales.'
196 options = {}
197 if args.data is None and args.bins is None:
198 # Offset bins reproduce the interleaved bars visible in the reference.
199 options = dict(bins={'Group A':np.arange(-70.,71.,10.),
200 'Group B':np.arange(-72.,79.,10.),
201 'Group C':np.arange(-68.,77.,8.)},
202 ylimits=[(0,29),(0,27),(0,33.5)],ytick_step=5)
203 else:
204 options['bins'] = args.bins if args.bins is not None else 14
205 if args.reference_colors:
206 options['colors'] = ['#E74C3C','#40516D','#22998D']
207 fig, stats = plot_chart(groups,xlabel=args.xlabel,fit=not args.no_fit,note=note,**options)
208 args.output.parent.mkdir(parents=True,exist_ok=True)
209 for suffix in ('png','pdf'):
210 fig.savefig(args.output.with_suffix('.'+suffix),dpi=300,facecolor='white',
211 bbox_inches='tight',pad_inches=.2)
212 args.output.with_suffix('.json').write_text(json.dumps(stats,ensure_ascii=False,indent=2),encoding='utf8')
213 if args.data is None:
214 with args.output.with_suffix('.csv').open('w',encoding='utf8',newline='') as stream:
215 writer=csv.writer(stream);writer.writerow(['group','value'])
216 for name,values in groups.items():
217 writer.writerows((name,float(v)) for v in values)
218 plt.close(fig)
219 print('Saved PNG, PDF and statistics:',args.output)
220
221
222 if __name__ == '__main__':
223 main()