Skip to main content

oa/plot/
axes.rs

1//! `oa::plot::Axes` — one subplot inside an `oa::plot::Figure`.
2//!
3//! Records one optional raster base plus ordered vector artists.
4//! The parent Figure lowers the same commands through `Ui`'s GPU compositor
5//! for both live (`show`) and terminal (`save_to` / `render`) sinks.
6//!
7//! Donor reference: `oa/ui/plot/axes.h`, `oa/ui/plot/axes.cpp`
8
9use crate::Color;
10use crate::ui::types::PixelRect;
11
12// ── Axis scaling ──────────────────────────────────────────────────────────────
13
14/// Data-to-display transform applied per axis at replay.
15///
16/// The transform happens in display space: ticks, grid, artists, and
17/// `FigureView` pixel mapping all share `Axes::scaled_limits`.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum Scale {
20	/// Identity mapping.
21	#[default]
22	Linear,
23	/// Base-10 logarithm. Non-positive samples drop from artists; ticks land
24	/// on whole decades. Device-resident series (`plot_matrix`) cannot be
25	/// transformed host-side and require linear axes.
26	Log10,
27	/// Symmetric log: linear inside `±SYMLOG_LINTHRESH`, logarithmic beyond.
28	/// Zero and negative data stay on the axis; ticks land on symmetric
29	/// decades plus zero.
30	Symlog,
31}
32
33/// Magnitude at which a [`Scale::Symlog`] axis switches from linear to log.
34pub const SYMLOG_LINTHRESH: f32 = 1.0;
35
36/// Transform one data value into display space; `NaN` drops the point.
37pub(super) fn scale_value(value: f32, scale: Scale) -> f32 {
38	match scale {
39		Scale::Linear => value,
40		Scale::Log10 => {
41			if value > 0.0 && value.is_finite() {
42				value.log10()
43			} else {
44				f32::NAN
45			}
46		}
47		Scale::Symlog => {
48			if !value.is_finite() {
49				return f32::NAN;
50			}
51			let magnitude = value.abs();
52			if magnitude <= SYMLOG_LINTHRESH {
53				value
54			} else {
55				value.signum() * SYMLOG_LINTHRESH * (1.0 + (magnitude / SYMLOG_LINTHRESH).log10())
56			}
57		}
58	}
59}
60
61/// Inverse of [`scale_value`], used for readouts and limit write-back.
62pub(super) fn unscale_value(value: f32, scale: Scale) -> f32 {
63	match scale {
64		Scale::Linear => value,
65		Scale::Log10 => 10f32.powf(value),
66		Scale::Symlog => {
67			let magnitude = value.abs();
68			if magnitude <= SYMLOG_LINTHRESH {
69				value
70			} else {
71				value.signum() * SYMLOG_LINTHRESH * 10f32.powf(magnitude / SYMLOG_LINTHRESH - 1.0)
72			}
73		}
74	}
75}
76
77/// Resolve one axis' raw `[lo, hi]` into display space.
78///
79/// A logarithmic axis whose lower bound is non-positive floors at the
80/// smallest positive recorded value; an axis without any positive data
81/// falls back to the `[0, 1]` display decade.
82fn scaled_axis(lo: f32, hi: f32, scale: Scale, positive_min: Option<f32>) -> (f32, f32) {
83	match scale {
84		Scale::Linear => (lo, hi),
85		Scale::Log10 => {
86			let lo = if lo.is_finite() && lo > 0.0 {
87				lo
88			} else if let Some(min) = positive_min {
89				min
90			} else {
91				return (0.0, 1.0);
92			};
93			let hi = if hi.is_finite() && hi > lo {
94				hi
95			} else {
96				lo * 10.0
97			};
98			(lo.log10(), hi.log10())
99		}
100		Scale::Symlog => {
101			let lo = scale_value(lo, scale);
102			let hi = scale_value(hi, scale);
103			if lo.is_finite() && hi.is_finite() && lo < hi {
104				(lo, hi)
105			} else {
106				(-SYMLOG_LINTHRESH, SYMLOG_LINTHRESH)
107			}
108		}
109	}
110}
111
112/// Axis tick label presentation paired with explicit tick positions.
113///
114/// Applies to ticks recorded through [`Axes::xticks`]/[`Axes::yticks`];
115/// `Labels` pairs one string per explicit value and requires equal lengths.
116#[derive(Clone, Debug, Default)]
117pub enum TickFormat {
118	/// Precision derived from the explicit positions' spacing.
119	#[default]
120	Auto,
121	/// Fixed decimal places — `Decimals(2)` renders `1.25`.
122	Decimals(usize),
123	/// Scientific notation — `1.2e3`.
124	Scientific,
125	/// Caller-provided labels, one per explicit tick value in order.
126	Labels(Vec<String>),
127}
128
129// ── Style descriptors ─────────────────────────────────────────────────────────
130
131/// Per-series line style.
132#[derive(Clone, Debug)]
133pub struct LineStyle {
134	/// Alpha-zero selects the next deterministic theme palette color.
135	pub color: Color,
136	pub label: String,
137	pub width: f32,
138	pub antialias_samples: u32,
139	/// Draw as a step function: each y value holds to the next x
140	/// (matplotlib `steps-post`).
141	pub step: bool,
142	/// Skip rendering while keeping the palette slot and legend entry.
143	pub hidden: bool,
144}
145
146impl Default for LineStyle {
147	fn default() -> Self {
148		Self {
149			color: Color::new(0.0, 0.0, 0.0, 0.0), // palette auto
150			label: String::new(),
151			width: 1.35,
152			antialias_samples: 4,
153			step: false,
154			hidden: false,
155		}
156	}
157}
158
159/// Per-series scatter style.
160#[derive(Clone, Debug)]
161pub struct ScatterStyle {
162	pub color: Color,
163	pub label: String,
164	pub radius: f32,
165	/// Skip rendering while keeping the palette slot and legend entry.
166	pub hidden: bool,
167}
168
169impl Default for ScatterStyle {
170	fn default() -> Self {
171		Self {
172			color: Color::new(0.0, 0.0, 0.0, 0.0),
173			label: String::new(),
174			radius: 3.0,
175			hidden: false,
176		}
177	}
178}
179
180/// Per-series bar style.
181#[derive(Clone, Debug)]
182pub struct BarStyle {
183	pub color: Color,
184	pub label: String,
185	/// Gap fraction between bars `[0, 0.95]`.
186	pub gap: f32,
187	/// Skip rendering while keeping the palette slot and legend entry.
188	pub hidden: bool,
189}
190
191impl Default for BarStyle {
192	fn default() -> Self {
193		Self {
194			color: Color::new(0.0, 0.0, 0.0, 0.0),
195			label: String::new(),
196			gap: 0.18,
197			hidden: false,
198		}
199	}
200}
201
202/// Dense row-major heatmap style.
203///
204/// Donor: `oa::plot::HeatmapStyle`.
205#[derive(Clone, Debug)]
206pub struct HeatmapStyle {
207	pub v_min: f32,
208	pub v_max: f32,
209	/// Colormap index evaluated by the shared `draw_heatmap` kernel:
210	/// 0 = plasma, 1 = viridis (default), 2 = blue-white-orange diverging,
211	/// 3 = grayscale.
212	pub colormap: u32,
213	/// Scale `v_min`/`v_max` automatically from data.
214	///
215	/// Only the host `heatmap` path can inspect values; the device-resident
216	/// `heatmap_matrix` path requires an explicit `v_min`/`v_max` range.
217	pub auto_scale: bool,
218	/// Draw a thin grid between cells.
219	pub show_grid: bool,
220	/// Reserve a strip at the right of the cell for a value-ramp colorbar
221	/// with min/mid/max labels.
222	pub colorbar: bool,
223}
224
225/// Box-summary style shared by every dataset in one `boxplot` call.
226#[derive(Clone, Debug)]
227pub struct BoxStyle {
228	/// Alpha-zero cycles the theme palette per dataset slot.
229	pub color: Color,
230	pub label: String,
231	/// Box width as a fraction of the dataset slot `[0, 0.95]`.
232	pub width: f32,
233	/// Whisker reach in interquartile-range units (matplotlib `whis`).
234	pub whisk: f32,
235	/// Skip rendering while keeping the palette slot and legend entry.
236	pub hidden: bool,
237}
238
239impl Default for BoxStyle {
240	fn default() -> Self {
241		Self {
242			color: Color::new(0.0, 0.0, 0.0, 0.0),
243			label: String::new(),
244			width: 0.5,
245			whisk: 1.5,
246			hidden: false,
247		}
248	}
249}
250
251impl Default for HeatmapStyle {
252	fn default() -> Self {
253		Self {
254			v_min: 0.0,
255			v_max: 1.0,
256			colormap: 1, // viridis
257			auto_scale: true,
258			show_grid: true,
259			colorbar: false,
260		}
261	}
262}
263
264// ── Internal command records ──────────────────────────────────────────────────
265
266/// Insertion-order artist kind — mirrors the donor's `ArtistRef`.
267#[derive(Clone, Copy, Debug, PartialEq, Eq)]
268pub(super) enum ArtistKind {
269	Line,
270	Scatter,
271	Bar,
272	/// Device-resident `Matrix` line series.
273	LineMatrix,
274	/// Host ring-buffer series appended through `Axes::stream_push`.
275	Stream,
276	/// Filled band between two y curves.
277	Band,
278	/// Quartile boxes over one or more datasets.
279	BoxPlot,
280}
281
282/// Retained commands within one Axes.
283#[derive(Default, Clone)]
284pub(super) struct AxesCommands {
285	pub(super) title: String,
286	pub(super) title_color: Color,
287	pub(super) caption: String,
288	pub(super) caption_color: Color,
289	pub(super) x_label: String,
290	pub(super) y_label: String,
291	pub(super) imshow: Option<ImshowCmd>,
292	pub(super) heatmap: Option<Heatmap>,
293	pub(super) heatmap_matrix: Option<HeatmapMatrixCmd>,
294	pub(super) lines: Vec<LineCmd>,
295	pub(super) scatters: Vec<ScatterCmd>,
296	pub(super) bars: Vec<BarCmd>,
297	pub(super) line_matrices: Vec<LineMatrixCmd>,
298	pub(super) streams: Vec<StreamCmd>,
299	pub(super) bands: Vec<BandCmd>,
300	pub(super) boxes: Vec<BoxCmd>,
301	pub(super) annotations: Vec<AnnotationCmd>,
302	/// Insertion-order list of artists — used by Figure to replay in call order.
303	pub(super) artists: Vec<ArtistKind>,
304	pub(super) limits: Option<LimitsCmd>,
305	pub(super) x_scale: Scale,
306	pub(super) y_scale: Scale,
307	/// Explicit data-space tick positions; `None` = nice-number locator.
308	pub(super) x_ticks: Option<Vec<f32>>,
309	pub(super) y_ticks: Option<Vec<f32>>,
310	pub(super) x_tick_format: TickFormat,
311	pub(super) y_tick_format: TickFormat,
312	pub(super) categories: Vec<String>,
313	pub(super) show_grid: bool,
314	pub(super) show_legend: bool,
315	pub(super) border_color: Option<Color>,
316}
317
318impl AxesCommands {
319	pub(super) fn new() -> Self {
320		Self {
321			show_grid: true,
322			show_legend: true,
323			..Default::default()
324		}
325	}
326}
327
328#[derive(Clone)]
329pub(super) struct ImshowCmd {
330	pub(super) texture: crate::Texture,
331}
332
333#[derive(Clone)]
334pub(super) struct Heatmap {
335	pub(super) values: Vec<f32>,
336	pub(super) rows: i32,
337	pub(super) cols: i32,
338	pub(super) style: HeatmapStyle,
339}
340
341/// Device-resident dense heatmap; the matrix stays on the GPU.
342#[derive(Clone)]
343pub(super) struct HeatmapMatrixCmd {
344	pub(super) values: crate::Matrix,
345	pub(super) style: HeatmapStyle,
346}
347
348#[derive(Clone)]
349pub(super) struct LineCmd {
350	pub(super) x: Vec<f32>,
351	pub(super) y: Vec<f32>,
352	pub(super) style: LineStyle,
353}
354
355#[derive(Clone)]
356pub(super) struct ScatterCmd {
357	pub(super) x: Vec<f32>,
358	pub(super) y: Vec<f32>,
359	pub(super) style: ScatterStyle,
360}
361
362#[derive(Clone)]
363pub(super) struct BarCmd {
364	pub(super) y: Vec<f32>,
365	/// `(index, size)` inside each x slot for grouped bars; `None` = full slot.
366	pub(super) group: Option<(usize, usize)>,
367	/// Running-sum baseline per bar for stacked layers; `None` = zero base.
368	pub(super) stack_base: Option<Vec<f32>>,
369	pub(super) style: BarStyle,
370}
371
372/// Device-resident line series; the matrix stays on the GPU.
373///
374/// `xy` selects the layout contract: `true` = rank-2 `[2, N]` with one X
375/// block followed by one Y block (the `draw_plot_line` explicit-XY ABI);
376/// `false` = rank-1 `[N]` y-vs-index.
377#[derive(Clone)]
378pub(super) struct LineMatrixCmd {
379	pub(super) values: crate::Matrix,
380	pub(super) xy: bool,
381	pub(super) style: LineStyle,
382}
383
384/// Host ring-buffer line series for live data.
385///
386/// The window's x domain is `[0, capacity - 1]` sample indices; samples
387/// arrive through `Axes::stream_push` and the oldest drop once `len` reaches
388/// `capacity`, so a full window scrolls like a rolling trace.
389#[derive(Clone)]
390pub(super) struct StreamCmd {
391	pub(super) values: Vec<f32>,
392	pub(super) head: usize,
393	pub(super) len: usize,
394	pub(super) style: LineStyle,
395}
396
397impl StreamCmd {
398	/// Append one sample, dropping the oldest when the window is full.
399	fn push(&mut self, value: f32) {
400		let capacity = self.values.len();
401		if self.len < capacity {
402			self.values[(self.head + self.len) % capacity] = value;
403			self.len += 1;
404		} else {
405			self.values[self.head] = value;
406			self.head = (self.head + 1) % capacity;
407		}
408	}
409
410	/// Window contents in draw order (oldest first).
411	pub(super) fn ordered(&self) -> impl Iterator<Item = f32> + '_ {
412		let capacity = self.values.len();
413		(0..self.len).map(move |index| self.values[(self.head + index) % capacity])
414	}
415}
416
417/// One box-summary artist; each entry is one dataset's quartiles.
418///
419/// Quartiles are resolved eagerly at record time so replay stays free of
420/// data inspection and automatic limits can read the whisker extents.
421#[derive(Clone)]
422pub(super) struct BoxCmd {
423	/// `(slot, q1, median, q3, whisker_lo, whisker_hi)` per dataset.
424	pub(super) summaries: Vec<(f32, f32, f32, f32, f32, f32)>,
425	pub(super) style: BoxStyle,
426}
427
428/// Filled band between two host y curves at x = 0..n-1.
429///
430/// The band is the matplotlib `fill_between` / error-band primitive: replay
431/// shades the region between `y_lo` and `y_hi` with `style.color`.
432#[derive(Clone)]
433pub(super) struct BandCmd {
434	pub(super) y_lo: Vec<f32>,
435	pub(super) y_hi: Vec<f32>,
436	pub(super) style: LineStyle,
437}
438
439/// Data-space text annotation.
440#[derive(Clone)]
441pub(super) struct AnnotationCmd {
442	pub(super) text: String,
443	pub(super) x: f32,
444	pub(super) y: f32,
445}
446
447#[derive(Clone, Debug)]
448pub(super) struct LimitsCmd {
449	pub(super) x_min: f32,
450	pub(super) x_max: f32,
451	pub(super) y_min: f32,
452	pub(super) y_max: f32,
453}
454
455/// One resolved legend entry, in artist insertion order.
456///
457/// `row` is `usize::MAX` for unlabeled artists (no legend row) and the
458/// drawn row index otherwise; `artist` is the `cmds.artists` position used
459/// by `set_artist_hidden`.
460pub(super) struct LegendEntry {
461	pub(super) artist: usize,
462	pub(super) label: String,
463	pub(super) color: Color,
464	pub(super) hidden: bool,
465	pub(super) row: usize,
466}
467
468/// Pixels reserved at the right of a cell for a heatmap colorbar.
469pub(super) const COLORBAR_RESERVE: u32 = 46;
470
471/// Data viewport and surrounding text bands within one figure cell.
472pub(super) struct AxesLayout {
473	pub(super) plot: PixelRect,
474	pub(super) title: PixelRect,
475	pub(super) caption: PixelRect,
476	pub(super) x_ticks: PixelRect,
477	pub(super) y_ticks: PixelRect,
478	pub(super) x_label: PixelRect,
479	pub(super) y_label: PixelRect,
480}
481
482const LEGEND_WIDTH: u32 = 124;
483const LEGEND_INSET: u32 = 6;
484const LEGEND_ROW_HEIGHT: u32 = 15;
485
486/// Legend geometry shared by figure replay and `FigureView` hit-testing.
487pub(super) fn legend_row_rect(rect: PixelRect, row: usize) -> PixelRect {
488	let w = rect.w.saturating_sub(2 * LEGEND_INSET).min(LEGEND_WIDTH);
489	let h = rect.h.saturating_sub(2 * LEGEND_INSET);
490	let offset = row.saturating_mul(LEGEND_ROW_HEIGHT as usize);
491	if w < 38 || offset.saturating_add(LEGEND_ROW_HEIGHT as usize) > h as usize {
492		return PixelRect::default();
493	}
494	PixelRect::new(
495		rect.x + (rect.w - w - LEGEND_INSET) as i32,
496		rect.y + LEGEND_INSET as i32 + offset as i32,
497		w,
498		LEGEND_ROW_HEIGHT,
499	)
500}
501
502// ── Axes ──────────────────────────────────────────────────────────────────────
503
504/// One subplot inside an `oa::plot::Figure`.
505#[derive(Clone)]
506pub struct Axes {
507	pub(super) cmds: AxesCommands,
508	/// Artist index kept at full strength while the rest render dimmed —
509	/// `FigureView` sets this from legend hover.
510	pub(super) highlight: Option<usize>,
511}
512
513impl Default for Axes {
514	fn default() -> Self {
515		Self {
516			cmds: AxesCommands::new(),
517			highlight: None,
518		}
519	}
520}
521
522impl Axes {
523	/// Set the axes title rendered above its plot region.
524	///
525	/// `color` with alpha zero (the default) uses the theme text color.
526	pub fn title(&mut self, text: &str) {
527		self.title_color(text, Color::new(0.0, 0.0, 0.0, 0.0));
528	}
529
530	/// Set the axes title with an explicit text color.
531	pub fn title_color(&mut self, text: &str, color: Color) {
532		self.cmds.title = text.to_owned();
533		self.cmds.title_color = color;
534	}
535
536	/// Set the secondary caption line below the title.
537	///
538	/// Used by the image-classify tutorial to show the ground-truth label.
539	/// Alpha-zero color uses the theme secondary text color.
540	pub fn caption(&mut self, text: &str) {
541		self.cmds.caption = text.to_owned();
542		self.cmds.caption_color = Color::new(0.0, 0.0, 0.0, 0.0);
543	}
544
545	/// Set caption with an explicit text color.
546	pub fn caption_color(&mut self, text: &str, color: Color) {
547		self.cmds.caption = text.to_owned();
548		self.cmds.caption_color = color;
549	}
550
551	/// Set the horizontal axis label centered below the tick labels.
552	pub fn x_label(&mut self, text: &str) {
553		self.cmds.x_label = text.to_owned();
554	}
555
556	/// Set the vertical axis label, read bottom-to-top to the left of the ticks.
557	pub fn y_label(&mut self, text: &str) {
558		self.cmds.y_label = text.to_owned();
559	}
560
561	/// Display a texture as a raster base for this axes. Standalone images
562	/// fit inside the subplot with their aspect ratio preserved.
563	pub fn imshow(&mut self, texture: crate::Texture) {
564		self.cmds.imshow = Some(ImshowCmd { texture });
565	}
566
567	/// Dense row-major heatmap.  Donor: `oa::plot::Axes::heatmap`.
568	pub fn heatmap(&mut self, values: &[f32], rows: i32, cols: i32, style: HeatmapStyle) {
569		let Some(count) = usize::try_from(rows).ok().and_then(|rows| {
570			usize::try_from(cols)
571				.ok()
572				.and_then(|cols| rows.checked_mul(cols))
573		}) else {
574			return;
575		};
576		if count == 0 || values.len() < count {
577			return;
578		}
579		self.cmds.heatmap = Some(Heatmap {
580			values: values[..count].to_vec(),
581			rows,
582			cols,
583			style,
584		});
585	}
586
587	/// Dense device-resident heatmap from a rank-2 `F32` `oa::Matrix`.
588	///
589	/// The matrix stays on the GPU; replay lowers it to one `draw_heatmap`
590	/// dispatch through the UI compositor. `style.auto_scale` cannot inspect
591	/// device data — callers must supply an explicit `v_min`/`v_max` range or
592	/// replay fails validation.
593	pub fn heatmap_matrix(&mut self, values: crate::Matrix, style: HeatmapStyle) {
594		if values.dtype() != crate::DType::F32 || values.shape().len() != 2 {
595			return;
596		}
597		self.cmds.heatmap_matrix = Some(HeatmapMatrixCmd { values, style });
598	}
599
600	/// Line plot: y-values vs index.  Repeated calls append ordered series.
601	pub fn plot(&mut self, y: &[f32], style: LineStyle) {
602		if y.is_empty() {
603			return;
604		}
605		let x: Vec<f32> = (0..y.len()).map(|i| i as f32).collect();
606		self.cmds.lines.push(LineCmd {
607			x,
608			y: y.to_vec(),
609			style,
610		});
611		self.cmds.artists.push(ArtistKind::Line);
612	}
613
614	/// Explicit X/Y line plot.
615	pub fn plot_xy(&mut self, x: &[f32], y: &[f32], style: LineStyle) {
616		if x.is_empty() || x.len() != y.len() {
617			return;
618		}
619		self.cmds.lines.push(LineCmd {
620			x: x.to_vec(),
621			y: y.to_vec(),
622			style,
623		});
624		self.cmds.artists.push(ArtistKind::Line);
625	}
626
627	/// Device-resident explicit-XY line series from an `F32` `[2, N]`
628	/// `oa::Matrix` laid out as one X block followed by one Y block.
629	///
630	/// The matrix stays on the GPU and is retained until composition
631	/// completes. Device data cannot be inspected host-side: the series does
632	/// not contribute to automatic limits (set `limits` explicitly or record
633	/// a host artist as well) and requires linear axes — a logarithmic axis
634	/// fails at replay rather than silently drawing untransformed data.
635	pub fn plot_matrix(&mut self, values: &crate::Matrix, style: LineStyle) {
636		let shape = values.shape();
637		if values.dtype() != crate::DType::F32 || shape.len() != 2 || shape[0] != 2 || shape[1] == 0 {
638			return;
639		}
640		self.cmds.line_matrices.push(LineMatrixCmd {
641			values: values.clone(),
642			xy: true,
643			style,
644		});
645		self.cmds.artists.push(ArtistKind::LineMatrix);
646	}
647
648	/// Device-resident y-vs-index line series from an `F32` `[N]` `oa::Matrix`.
649	///
650	/// Same device-resident contract as [`Axes::plot_matrix`]; x positions
651	/// are the sample indices `0..N-1`, which do contribute to automatic
652	/// x limits.
653	pub fn plot_matrix_y(&mut self, values: &crate::Matrix, style: LineStyle) {
654		if values.dtype() != crate::DType::F32 || values.shape().len() != 1 || values.shape()[0] == 0 {
655			return;
656		}
657		self.cmds.line_matrices.push(LineMatrixCmd {
658			values: values.clone(),
659			xy: false,
660			style,
661		});
662		self.cmds.artists.push(ArtistKind::LineMatrix);
663	}
664
665	/// Data-space text annotation anchored at `(x, y)`.
666	///
667	/// The text renders just above the data point; non-finite or
668	/// scale-dropped points are skipped at replay.
669	pub fn annotate(&mut self, text: &str, x: f32, y: f32) {
670		if text.is_empty() {
671			return;
672		}
673		self.cmds.annotations.push(AnnotationCmd {
674			text: text.to_owned(),
675			x,
676			y,
677		});
678	}
679
680	/// Category labels replacing numeric x tick labels at bar positions.
681	///
682	/// Pass one label per bar slot; an empty list restores numeric ticks.
683	pub fn categories(&mut self, labels: &[&str]) {
684		self.cmds.categories = labels.iter().map(|label| (*label).to_owned()).collect();
685	}
686
687	/// Set the x axis scaling (default: linear).
688	pub fn xscale(&mut self, scale: Scale) {
689		self.cmds.x_scale = scale;
690	}
691
692	/// Set the y axis scaling (default: linear).
693	pub fn yscale(&mut self, scale: Scale) {
694		self.cmds.y_scale = scale;
695	}
696
697	/// Explicit x tick positions in data space.
698	///
699	/// Positions map through the x scale at replay — a `Log10` axis drops
700	/// non-positive values — and share grid placement with the labels.
701	/// An empty slice restores the automatic nice-number locator.
702	pub fn xticks(&mut self, values: &[f32]) {
703		self.cmds.x_ticks = if values.is_empty() {
704			None
705		} else {
706			Some(values.to_vec())
707		};
708	}
709
710	/// Explicit y tick positions in data space; see [`Axes::xticks`].
711	pub fn yticks(&mut self, values: &[f32]) {
712		self.cmds.y_ticks = if values.is_empty() {
713			None
714		} else {
715			Some(values.to_vec())
716		};
717	}
718
719	/// Label presentation for explicit [`Axes::xticks`] positions.
720	pub fn xformat(&mut self, format: TickFormat) {
721		self.cmds.x_tick_format = format;
722	}
723
724	/// Label presentation for explicit [`Axes::yticks`] positions.
725	pub fn yformat(&mut self, format: TickFormat) {
726		self.cmds.y_tick_format = format;
727	}
728
729	/// Point cloud scatter.
730	pub fn scatter(&mut self, x: &[f32], y: &[f32], style: ScatterStyle) {
731		if x.is_empty() || x.len() != y.len() {
732			return;
733		}
734		self.cmds.scatters.push(ScatterCmd {
735			x: x.to_vec(),
736			y: y.to_vec(),
737			style,
738		});
739		self.cmds.artists.push(ArtistKind::Scatter);
740	}
741
742	/// Vertical bar chart at x = 0..n-1.
743	pub fn bar(&mut self, y: &[f32], style: BarStyle) {
744		if y.is_empty() {
745			return;
746		}
747		self.cmds.bars.push(BarCmd {
748			y: y.to_vec(),
749			group: None,
750			stack_base: None,
751			style,
752		});
753		self.cmds.artists.push(ArtistKind::Bar);
754	}
755
756	/// Grouped bar chart — `series[i]` shares each x slot side-by-side.
757	///
758	/// `styles` pairs per layer; a short list falls back to defaults (palette
759	/// colors). Each layer is its own artist, so legend rows and visibility
760	/// toggling work per series.
761	pub fn bar_grouped(&mut self, series: &[&[f32]], styles: &[BarStyle]) {
762		let size = series.len();
763		if size == 0 || series.iter().any(|layer| layer.is_empty()) {
764			return;
765		}
766		for (index, layer) in series.iter().enumerate() {
767			self.cmds.bars.push(BarCmd {
768				y: (*layer).to_vec(),
769				group: Some((index, size)),
770				stack_base: None,
771				style: styles.get(index).cloned().unwrap_or_default(),
772			});
773			self.cmds.artists.push(ArtistKind::Bar);
774		}
775	}
776
777	/// Stacked bar chart — `series[i]` accumulates on top of the layers
778	/// before it.
779	///
780	/// Style and artist semantics match [`Axes::bar_grouped`]; each layer's
781	/// baseline is the running sum of the previous layers' values.
782	pub fn bar_stacked(&mut self, series: &[&[f32]], styles: &[BarStyle]) {
783		if series.is_empty() || series.iter().any(|layer| layer.is_empty()) {
784			return;
785		}
786		let count = series[0].len();
787		if series.iter().any(|layer| layer.len() != count) {
788			return;
789		}
790		let mut base = vec![0.0_f32; count];
791		for (index, layer) in series.iter().enumerate() {
792			self.cmds.bars.push(BarCmd {
793				y: (*layer).to_vec(),
794				group: None,
795				stack_base: Some(base.clone()),
796				style: styles.get(index).cloned().unwrap_or_default(),
797			});
798			self.cmds.artists.push(ArtistKind::Bar);
799			for (acc, &value) in base.iter_mut().zip(layer.iter()) {
800				*acc += if value.is_finite() { value } else { 0.0 };
801			}
802		}
803	}
804
805	/// Begin a rolling line series of fixed `capacity` samples.
806	///
807	/// Returns the series handle for [`Axes::stream_push`]. The window's x
808	/// domain is the sample indices `0..capacity-1`, so the trace fills from
809	/// the left and then scrolls as the oldest samples drop.
810	pub fn stream(&mut self, capacity: usize, style: LineStyle) -> usize {
811		let index = self.cmds.streams.len();
812		self.cmds.streams.push(StreamCmd {
813			values: vec![0.0; capacity.max(1)],
814			head: 0,
815			len: 0,
816			style,
817		});
818		self.cmds.artists.push(ArtistKind::Stream);
819		index
820	}
821
822	/// Append samples to a [`Axes::stream`] series.
823	///
824	/// Out-of-range handles are ignored, matching the silent-skip contract of
825	/// the other recording methods.
826	pub fn stream_push(&mut self, series: usize, values: &[f32]) {
827		if let Some(stream) = self.cmds.streams.get_mut(series) {
828			for &value in values {
829				stream.push(value);
830			}
831		}
832	}
833
834	/// Fill the band between two equal-length y curves at x = 0..n-1.
835	///
836	/// The error-band / `fill_between` primitive: `style.color` (alpha
837	/// included) tints the shaded region. Band x positions are the sample
838	/// indices, so a non-linear x axis is rejected at replay.
839	pub fn band(&mut self, y_lo: &[f32], y_hi: &[f32], style: LineStyle) {
840		if y_lo.is_empty() || y_lo.len() != y_hi.len() {
841			return;
842		}
843		self.cmds.bands.push(BandCmd {
844			y_lo: y_lo.to_vec(),
845			y_hi: y_hi.to_vec(),
846			style,
847		});
848		self.cmds.artists.push(ArtistKind::Band);
849	}
850
851	/// Box-and-whisker summary over one or more datasets.
852	///
853	/// Each dataset becomes one box centered on its own x slot, palette-colored
854	/// in order. Quartiles use linear interpolation (matplotlib default) and
855	/// whiskers extend `style.whisk` × IQR, clamped to the data extremes.
856	pub fn boxplot(&mut self, datasets: &[&[f32]], style: BoxStyle) {
857		if datasets.is_empty() {
858			return;
859		}
860		let mut summaries = Vec::with_capacity(datasets.len());
861		for (index, dataset) in datasets.iter().enumerate() {
862			let mut sorted: Vec<f32> = dataset.iter().copied().filter(|v| v.is_finite()).collect();
863			if sorted.is_empty() {
864				continue;
865			}
866			sorted.sort_by(f32::total_cmp);
867			let q1 = percentile(&sorted, 0.25);
868			let median = percentile(&sorted, 0.5);
869			let q3 = percentile(&sorted, 0.75);
870			let iqr = (q3 - q1) * style.whisk;
871			let lo = sorted
872				.iter()
873				.copied()
874				.find(|&v| v >= q1 - iqr)
875				.unwrap_or(sorted[0]);
876			let hi = sorted
877				.iter()
878				.copied()
879				.rev()
880				.find(|&v| v <= q3 + iqr)
881				.unwrap_or(sorted[sorted.len() - 1]);
882			summaries.push((index as f32, q1, median, q3, lo, hi));
883		}
884		if summaries.is_empty() {
885			return;
886		}
887		self.cmds.boxes.push(BoxCmd { summaries, style });
888		self.cmds.artists.push(ArtistKind::BoxPlot);
889	}
890
891	/// Histogram: bin `values` into `bins` bars.
892	pub fn histogram(&mut self, values: &[f32], bins: i32, style: BarStyle) {
893		if bins <= 0 || values.is_empty() {
894			return;
895		}
896		let bins = (bins as usize).min(4096);
897		let finite: Vec<f32> = values.iter().copied().filter(|v| v.is_finite()).collect();
898		if finite.is_empty() {
899			return;
900		}
901		let v_min = finite.iter().cloned().fold(f32::INFINITY, f32::min);
902		let v_max = finite.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
903		let range = (v_max - v_min).max(1e-8);
904		let mut counts = vec![0.0f32; bins];
905		for &v in &finite {
906			let idx = (((v - v_min) / range) * bins as f32) as usize;
907			counts[idx.min(bins - 1)] += 1.0;
908		}
909		self.bar(&counts, style);
910	}
911
912	/// Fixed data limits; degenerate input restores auto-limits.
913	pub fn limits(&mut self, x_min: f32, x_max: f32, y_min: f32, y_max: f32) {
914		if [x_min, x_max, y_min, y_max]
915			.iter()
916			.all(|value| value.is_finite())
917			&& x_min < x_max
918			&& y_min < y_max
919		{
920			self.cmds.limits = Some(LimitsCmd {
921				x_min,
922				x_max,
923				y_min,
924				y_max,
925			});
926		} else {
927			self.auto_limits();
928		}
929	}
930
931	/// Restore automatic data-driven limits.
932	pub fn auto_limits(&mut self) {
933		self.cmds.limits = None;
934	}
935
936	/// Toggle the background grid (default: on).
937	pub fn grid(&mut self, visible: bool) {
938		self.cmds.show_grid = visible;
939	}
940
941	/// Toggle the labeled-series legend (default: on).
942	pub fn legend(&mut self, visible: bool) {
943		self.cmds.show_legend = visible;
944	}
945
946	/// Border color around the axes rect (default: none).
947	pub fn border_color(&mut self, color: Color) {
948		self.cmds.border_color = Some(color);
949	}
950
951	/// Clear all recorded commands.
952	pub fn clear(&mut self) {
953		self.cmds = AxesCommands::new();
954	}
955
956	/// Number of recorded artists in insertion order.
957	pub fn artist_count(&self) -> usize {
958		self.cmds.artists.len()
959	}
960
961	/// Visibility flag of the `index`-th artist in insertion order.
962	pub fn artist_hidden(&self, index: usize) -> Option<bool> {
963		let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
964			(0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
965		for (position, kind) in self.cmds.artists.iter().enumerate() {
966			let hidden = match kind {
967				ArtistKind::Line => self.cmds.lines.get(line).map(|cmd| cmd.style.hidden),
968				ArtistKind::Scatter => self.cmds.scatters.get(scatter).map(|cmd| cmd.style.hidden),
969				ArtistKind::Bar => self.cmds.bars.get(bar).map(|cmd| cmd.style.hidden),
970				ArtistKind::LineMatrix => self
971					.cmds
972					.line_matrices
973					.get(matrix)
974					.map(|cmd| cmd.style.hidden),
975				ArtistKind::Stream => self.cmds.streams.get(stream).map(|cmd| cmd.style.hidden),
976				ArtistKind::Band => self.cmds.bands.get(band).map(|cmd| cmd.style.hidden),
977				ArtistKind::BoxPlot => self.cmds.boxes.get(bx).map(|cmd| cmd.style.hidden),
978			};
979			if position == index {
980				return hidden;
981			}
982			match kind {
983				ArtistKind::Line => line += 1,
984				ArtistKind::Scatter => scatter += 1,
985				ArtistKind::Bar => bar += 1,
986				ArtistKind::LineMatrix => matrix += 1,
987				ArtistKind::Stream => stream += 1,
988				ArtistKind::Band => band += 1,
989				ArtistKind::BoxPlot => bx += 1,
990			}
991		}
992		None
993	}
994
995	/// Show or hide the `index`-th artist in insertion order.
996	///
997	/// Hidden artists keep their palette slot and legend entry but skip
998	/// rendering; `FigureView` legend toggling writes this flag.
999	pub fn set_artist_hidden(&mut self, index: usize, hidden: bool) {
1000		let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
1001			(0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
1002		for (position, kind) in self.cmds.artists.iter().enumerate() {
1003			if position == index {
1004				match kind {
1005					ArtistKind::Line => {
1006						if let Some(cmd) = self.cmds.lines.get_mut(line) {
1007							cmd.style.hidden = hidden;
1008						}
1009					}
1010					ArtistKind::Scatter => {
1011						if let Some(cmd) = self.cmds.scatters.get_mut(scatter) {
1012							cmd.style.hidden = hidden;
1013						}
1014					}
1015					ArtistKind::Bar => {
1016						if let Some(cmd) = self.cmds.bars.get_mut(bar) {
1017							cmd.style.hidden = hidden;
1018						}
1019					}
1020					ArtistKind::LineMatrix => {
1021						if let Some(cmd) = self.cmds.line_matrices.get_mut(matrix) {
1022							cmd.style.hidden = hidden;
1023						}
1024					}
1025					ArtistKind::Stream => {
1026						if let Some(cmd) = self.cmds.streams.get_mut(stream) {
1027							cmd.style.hidden = hidden;
1028						}
1029					}
1030					ArtistKind::Band => {
1031						if let Some(cmd) = self.cmds.bands.get_mut(band) {
1032							cmd.style.hidden = hidden;
1033						}
1034					}
1035					ArtistKind::BoxPlot => {
1036						if let Some(cmd) = self.cmds.boxes.get_mut(bx) {
1037							cmd.style.hidden = hidden;
1038						}
1039					}
1040				}
1041				return;
1042			}
1043			match kind {
1044				ArtistKind::Line => line += 1,
1045				ArtistKind::Scatter => scatter += 1,
1046				ArtistKind::Bar => bar += 1,
1047				ArtistKind::LineMatrix => matrix += 1,
1048				ArtistKind::Stream => stream += 1,
1049				ArtistKind::Band => band += 1,
1050				ArtistKind::BoxPlot => bx += 1,
1051			}
1052		}
1053	}
1054
1055	/// Highlight the `index`-th artist in insertion order, dimming the rest.
1056	///
1057	/// `None` restores uniform emphasis; `FigureView` legend hover writes this.
1058	pub fn set_series_highlight(&mut self, index: Option<usize>) {
1059		self.highlight = index;
1060	}
1061
1062	// ── Shared layout / legend helpers ──────────────────────────────────────
1063
1064	/// Whether the cell records data on numeric or categorical axes.
1065	pub(super) fn has_ticks(&self) -> bool {
1066		!self.cmds.artists.is_empty()
1067			|| !self.cmds.annotations.is_empty()
1068			|| self.cmds.limits.is_some()
1069			|| self.cmds.x_ticks.is_some()
1070			|| self.cmds.y_ticks.is_some()
1071			|| !self.cmds.categories.is_empty()
1072	}
1073
1074	/// Reserve title, label, tick and colorbar bands around the data viewport.
1075	///
1076	/// Figure replay and `FigureView` hit-testing share this helper so
1077	/// pixel↔data mapping always agrees with the drawn artists.
1078	pub(super) fn layout(&self, cell: PixelRect) -> AxesLayout {
1079		let colorbar = self
1080			.cmds
1081			.heatmap
1082			.as_ref()
1083			.is_some_and(|heatmap| heatmap.style.colorbar)
1084			|| self
1085				.cmds
1086				.heatmap_matrix
1087				.as_ref()
1088				.is_some_and(|heatmap| heatmap.style.colorbar);
1089		// Keep at least half the cell available for data, including when a
1090		// workspace pane is temporarily too small to display all its labels.
1091		let reserve = |budget: &mut u32, pixels: u32| {
1092			let pixels = pixels.min(*budget);
1093			*budget -= pixels;
1094			pixels
1095		};
1096		let mut width_budget = cell.w / 2;
1097		let mut height_budget = cell.h / 2;
1098		let ticks = self.has_ticks() && cell.w >= 64 && cell.h >= 36;
1099		let colorbar_w = reserve(
1100			&mut width_budget,
1101			if colorbar { COLORBAR_RESERVE } else { 0 },
1102		);
1103		let y_label_w = reserve(
1104			&mut width_budget,
1105			if self.cmds.y_label.is_empty() { 0 } else { 19 },
1106		);
1107		let right = reserve(&mut width_budget, if ticks && !colorbar { 15 } else { 0 });
1108		let y_ticks_w = reserve(&mut width_budget, if ticks { 48 } else { 0 });
1109		let top = reserve(
1110			&mut height_budget,
1111			if !self.cmds.title.is_empty() {
1112				22
1113			} else if ticks {
1114				8
1115			} else {
1116				0
1117			},
1118		);
1119		let x_label_h = reserve(
1120			&mut height_budget,
1121			if self.cmds.x_label.is_empty() { 0 } else { 19 },
1122		);
1123		let x_ticks_h = reserve(&mut height_budget, if ticks { 18 } else { 0 });
1124		let caption_h = reserve(
1125			&mut height_budget,
1126			if self.cmds.caption.is_empty() { 0 } else { 18 },
1127		);
1128		let x = cell.x + (y_label_w + y_ticks_w) as i32;
1129		let y = cell.y + top as i32;
1130		let w = cell.w - y_label_w - y_ticks_w - right - colorbar_w;
1131		let h = cell.h - top - x_ticks_h - x_label_h - caption_h;
1132		let bottom = y + h as i32;
1133		AxesLayout {
1134			plot: PixelRect::new(x, y, w, h),
1135			title: PixelRect::new(x, cell.y, w, top),
1136			caption: PixelRect::new(x, bottom + (x_ticks_h + x_label_h) as i32, w, caption_h),
1137			x_ticks: PixelRect::new(cell.x, bottom, cell.w - colorbar_w, x_ticks_h),
1138			y_ticks: PixelRect::new(
1139				cell.x + y_label_w as i32,
1140				cell.y,
1141				y_ticks_w,
1142				top + h + x_ticks_h,
1143			),
1144			x_label: PixelRect::new(x, bottom + x_ticks_h as i32, w, x_label_h),
1145			y_label: PixelRect::new(cell.x, y, y_label_w, h),
1146		}
1147	}
1148
1149	/// Labeled-series legend entries in insertion order.
1150	///
1151	/// The palette counter advances for every alpha-zero artist — hidden and
1152	/// unlabeled included — so colors stay stable across legend toggles.
1153	/// `row` numbers only the labeled entries, matching the drawn rows.
1154	pub(super) fn legend_entries(&self, palette: &[crate::Color]) -> Vec<LegendEntry> {
1155		let mut entries = Vec::new();
1156		let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
1157			(0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
1158		let mut palette_idx = 0usize;
1159		for (position, kind) in self.cmds.artists.iter().enumerate() {
1160			let (label, color, hidden) = match kind {
1161				ArtistKind::Line => {
1162					let Some(cmd) = self.cmds.lines.get(line) else {
1163						continue;
1164					};
1165					line += 1;
1166					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
1167				}
1168				ArtistKind::Scatter => {
1169					let Some(cmd) = self.cmds.scatters.get(scatter) else {
1170						continue;
1171					};
1172					scatter += 1;
1173					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
1174				}
1175				ArtistKind::Bar => {
1176					let Some(cmd) = self.cmds.bars.get(bar) else {
1177						continue;
1178					};
1179					bar += 1;
1180					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
1181				}
1182				ArtistKind::LineMatrix => {
1183					let Some(cmd) = self.cmds.line_matrices.get(matrix) else {
1184						continue;
1185					};
1186					matrix += 1;
1187					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
1188				}
1189				ArtistKind::Stream => {
1190					let Some(cmd) = self.cmds.streams.get(stream) else {
1191						continue;
1192					};
1193					stream += 1;
1194					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
1195				}
1196				ArtistKind::Band => {
1197					let Some(cmd) = self.cmds.bands.get(band) else {
1198						continue;
1199					};
1200					band += 1;
1201					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
1202				}
1203				ArtistKind::BoxPlot => {
1204					let Some(cmd) = self.cmds.boxes.get(bx) else {
1205						continue;
1206					};
1207					bx += 1;
1208					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
1209				}
1210			};
1211			let color = if color.a == 0.0 {
1212				let resolved = palette[palette_idx % palette.len()];
1213				palette_idx += 1;
1214				resolved
1215			} else {
1216				color
1217			};
1218			entries.push(LegendEntry {
1219				artist: position,
1220				label: label.clone(),
1221				color,
1222				hidden,
1223				row: usize::MAX,
1224			});
1225		}
1226		let mut row = 0usize;
1227		for entry in &mut entries {
1228			if !entry.label.is_empty() {
1229				entry.row = row;
1230				row += 1;
1231			}
1232		}
1233		entries
1234	}
1235
1236	// ── Computed limits ───────────────────────────────────────────────────────
1237
1238	/// Compute the data-driven Y range from all recorded artists.
1239	pub(super) fn data_y_range(&self) -> (f32, f32) {
1240		let mut y_min = f32::INFINITY;
1241		let mut y_max = f32::NEG_INFINITY;
1242		for line in &self.cmds.lines {
1243			for &v in &line.y {
1244				if v.is_finite() {
1245					y_min = y_min.min(v);
1246					y_max = y_max.max(v);
1247				}
1248			}
1249		}
1250		for scatter in &self.cmds.scatters {
1251			for &value in &scatter.y {
1252				if value.is_finite() {
1253					y_min = y_min.min(value);
1254					y_max = y_max.max(value);
1255				}
1256			}
1257		}
1258		for bar in &self.cmds.bars {
1259			for (index, &v) in bar.y.iter().enumerate() {
1260				if v.is_finite() {
1261					let base = bar.stack_base.as_ref().map_or(0.0, |bases| bases[index]);
1262					y_min = y_min.min((base + v).min(base.min(0.0)));
1263					y_max = y_max.max((base + v).max(base.max(0.0)));
1264				}
1265			}
1266		}
1267		for stream in &self.cmds.streams {
1268			for value in stream.ordered() {
1269				if value.is_finite() {
1270					y_min = y_min.min(value);
1271					y_max = y_max.max(value);
1272				}
1273			}
1274		}
1275		for band in &self.cmds.bands {
1276			for &value in band.y_lo.iter().chain(&band.y_hi) {
1277				if value.is_finite() {
1278					y_min = y_min.min(value);
1279					y_max = y_max.max(value);
1280				}
1281			}
1282		}
1283		for boxes in &self.cmds.boxes {
1284			for &(_, _, _, _, lo, hi) in &boxes.summaries {
1285				y_min = y_min.min(lo);
1286				y_max = y_max.max(hi);
1287			}
1288		}
1289		if !y_min.is_finite() || !y_max.is_finite() {
1290			return (0.0, 1.0);
1291		}
1292		if (y_max - y_min).abs() < 1e-6 {
1293			return (y_min - 1.0, y_max + 1.0);
1294		}
1295		(y_min, y_max)
1296	}
1297
1298	/// Effective data limits `[x_min, x_max, y_min, y_max]` after explicit
1299	/// `limits` or automatic data-driven resolution. Interactive views use
1300	/// this to map pixel coordinates into data space.
1301	pub fn data_limits(&self) -> [f32; 4] {
1302		let limits = self.effective_limits();
1303		[limits.x_min, limits.x_max, limits.y_min, limits.y_max]
1304	}
1305
1306	/// The explicit `limits` override, or `None` when limits are data-driven.
1307	pub fn explicit_limits(&self) -> Option<[f32; 4]> {
1308		self
1309			.cmds
1310			.limits
1311			.as_ref()
1312			.map(|l| [l.x_min, l.x_max, l.y_min, l.y_max])
1313	}
1314
1315	/// Compute the effective data limits (explicit or automatic).
1316	pub(super) fn effective_limits(&self) -> LimitsCmd {
1317		if let Some(lim) = &self.cmds.limits {
1318			return lim.clone();
1319		}
1320		let (y_min, y_max) = self.data_y_range();
1321		let mut x_min = f32::INFINITY;
1322		let mut x_max = f32::NEG_INFINITY;
1323		for value in self
1324			.cmds
1325			.lines
1326			.iter()
1327			.flat_map(|line| line.x.iter())
1328			.chain(
1329				self
1330					.cmds
1331					.scatters
1332					.iter()
1333					.flat_map(|scatter| scatter.x.iter()),
1334			)
1335			.copied()
1336			.filter(|value| value.is_finite())
1337		{
1338			x_min = x_min.min(value);
1339			x_max = x_max.max(value);
1340		}
1341		for bar in &self.cmds.bars {
1342			x_min = x_min.min(0.0);
1343			x_max = x_max.max(bar.y.len().saturating_sub(1) as f32);
1344		}
1345		for matrix in &self.cmds.line_matrices {
1346			if !matrix.xy {
1347				let count = matrix.values.shape().first().copied().unwrap_or(0);
1348				x_min = x_min.min(0.0);
1349				x_max = x_max.max(count.saturating_sub(1) as f32);
1350			}
1351		}
1352		for stream in &self.cmds.streams {
1353			if stream.len == 0 {
1354				continue;
1355			}
1356			x_min = x_min.min(0.0);
1357			x_max = x_max.max(stream.values.len().saturating_sub(1) as f32);
1358		}
1359		for band in &self.cmds.bands {
1360			x_min = x_min.min(0.0);
1361			x_max = x_max.max(band.y_lo.len().saturating_sub(1) as f32);
1362		}
1363		for boxes in &self.cmds.boxes {
1364			x_min = x_min.min(0.0);
1365			x_max = x_max.max(boxes.summaries.len().saturating_sub(1) as f32);
1366		}
1367		if !x_min.is_finite() || !x_max.is_finite() || (x_max - x_min).abs() < 1e-6 {
1368			x_min = 0.0;
1369			x_max = 1.0;
1370		}
1371		LimitsCmd {
1372			x_min,
1373			x_max,
1374			y_min,
1375			y_max,
1376		}
1377	}
1378
1379	/// Effective limits transformed into display space by the axis scales.
1380	///
1381	/// Under linear scaling this equals `data_limits`; under `Log10` the
1382	/// ends are `log10` of the positive range (see [`scaled_axis`]).
1383	pub(super) fn scaled_limits(&self) -> LimitsCmd {
1384		let raw = self.effective_limits();
1385		let (x_min, x_max) = scaled_axis(
1386			raw.x_min,
1387			raw.x_max,
1388			self.cmds.x_scale,
1389			self.min_positive_x(),
1390		);
1391		let (y_min, y_max) = scaled_axis(
1392			raw.y_min,
1393			raw.y_max,
1394			self.cmds.y_scale,
1395			self.min_positive_y(),
1396		);
1397		LimitsCmd {
1398			x_min,
1399			x_max,
1400			y_min,
1401			y_max,
1402		}
1403	}
1404
1405	/// Smallest positive x value across host artists, for log limit floors.
1406	fn min_positive_x(&self) -> Option<f32> {
1407		let mut min = f32::INFINITY;
1408		for value in self.cmds.lines.iter().flat_map(|line| line.x.iter()).chain(
1409			self
1410				.cmds
1411				.scatters
1412				.iter()
1413				.flat_map(|scatter| scatter.x.iter()),
1414		) {
1415			if value.is_finite() && *value > 0.0 {
1416				min = min.min(*value);
1417			}
1418		}
1419		for bars in &self.cmds.bars {
1420			if bars.y.len() > 1 {
1421				min = min.min(1.0);
1422			}
1423		}
1424		min.is_finite().then_some(min)
1425	}
1426
1427	/// Smallest positive y value across host artists, for log limit floors.
1428	fn min_positive_y(&self) -> Option<f32> {
1429		let mut min = f32::INFINITY;
1430		for value in self
1431			.cmds
1432			.lines
1433			.iter()
1434			.flat_map(|line| line.y.iter())
1435			.chain(
1436				self
1437					.cmds
1438					.scatters
1439					.iter()
1440					.flat_map(|scatter| scatter.y.iter()),
1441			)
1442			.chain(self.cmds.bars.iter().flat_map(|bars| bars.y.iter()))
1443		{
1444			if value.is_finite() && *value > 0.0 {
1445				min = min.min(*value);
1446			}
1447		}
1448		min.is_finite().then_some(min)
1449	}
1450}
1451
1452/// Linear-interpolation percentile over sorted values (matplotlib default).
1453fn percentile(sorted: &[f32], q: f32) -> f32 {
1454	let pos = q * (sorted.len() - 1) as f32;
1455	let lo = pos.floor() as usize;
1456	let hi = (lo + 1).min(sorted.len() - 1);
1457	sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo as f32)
1458}