lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! Pre-backend chart configuration validation.

use std::collections::HashSet;

use crate::Error;

use crate::builder::PlotDescription;
use crate::data::{strict_source_normalized_strings, strict_source_strings};
use crate::spec::{
    CategoryOrder, HeatmapLayout, HistogramBins, HistogramComposite, HistogramStat, LinePathStyle,
    PlotKind, RegressionBand,
};

impl PlotDescription {
    pub(crate) fn validate_configuration(&self, kind: PlotKind) -> Result<(), Error> {
        self.validate_display_text()?;
        self.x_axis_spec().validate("x-axis")?;
        self.y_axis_spec().validate("y-axis")?;
        for (spec, logarithmic) in [
            (
                self.x_axis_spec(),
                kind == PlotKind::Forest && self.axis_scale_spec() == crate::spec::AxisScale::Log10,
            ),
            (self.y_axis_spec(), false),
        ] {
            spec.generation.validate_scale(logarithmic)?;
        }
        if !self.significance_annotations().is_empty() && !kind.supports_significance_annotations()
        {
            return Err(Error::Data(format!(
                "significance annotations are not supported for {kind:?}; use a supported categorical family or remove the annotations"
            ).into()));
        }
        if kind != PlotKind::Heatmap && self.heatmap_layout_spec() != HeatmapLayout::Cartesian {
            return Err(Error::Data(
                format!(
                    "{kind:?}: non-Cartesian HeatmapLayout is supported only by PlotKind::Heatmap"
                )
                .into(),
            ));
        }
        if kind != PlotKind::Heatmap && !self.heatmap_null_row_annotations_spec().is_empty() {
            return Err(Error::Data(format!(
                "{kind:?}: fully-null heatmap row annotations are supported only by PlotKind::Heatmap"
            ).into()));
        }
        if self.raincloud_geometry_input().is_some() && self.group_col().is_some() {
            return Err(Error::Data(
                "raincloud: Plot::series requires RaincloudInput::samples; remove .series(...) or construct the raincloud from samples"
                    .into(),
            ));
        }
        if self.has_raw_key_axis() {
            return Err(Error::Data(
                "direct raw-key coordinate input requires a categorical key axis".into(),
            ));
        }
        self.validate_value_alignment()?;
        if kind == PlotKind::Trajectory && self.automatic_axis_category_values(kind, true).is_some()
        {
            let condition = self
                .x_col()
                .ok_or_else(|| Error::Data("trajectory: condition column not set".into()))?;
            let crate::data::DataColumn::Category(values) =
                self.data_column(condition).ok_or_else(|| {
                    Error::Data(format!("unknown semantic value {condition:?}").into())
                })?
            else {
                return Err(Error::Data(
                    format!(
                        "trajectory: value {:?} must be categorical",
                        self.data_column(condition)
                            .expect("resolved condition")
                            .name()
                    )
                    .into(),
                ));
            };
            strict_source_normalized_strings(values, None, "trajectory", "condition")?;
        }
        self.validate_category_order_configuration(kind)?;
        self.validate_channel_configuration(kind)?;
        self.validate_interval_configuration(kind)?;
        self.validate_facet_configuration()?;
        self.validate_supplemental_configuration(kind)?;
        crate::layout::interior::InteriorRoute::classify(kind).validate(self)
    }

    pub(crate) fn validate_category_order_configuration(
        &self,
        kind: PlotKind,
    ) -> Result<(), Error> {
        if !matches!(self.category_order_spec(), CategoryOrder::Observed)
            && !matches!(
                kind,
                PlotKind::PointInterval
                    | PlotKind::Heatmap
                    | PlotKind::Bar
                    | PlotKind::HorizontalBar
                    | PlotKind::StackedBar
                    | PlotKind::StackedHorizontalBar
                    | PlotKind::Dumbbell
            )
        {
            return Err(Error::Data(
                format!("{kind:?}: primary category ordering is not supported").into(),
            ));
        }
        if kind != PlotKind::Heatmap
            && (!matches!(self.x_category_order_spec(), CategoryOrder::Observed)
                || !matches!(self.y_category_order_spec(), CategoryOrder::Observed))
        {
            return Err(Error::Data(
                format!(
                    "{kind:?}: x_category_order and y_category_order are supported only by Heatmap"
                )
                .into(),
            ));
        }
        if self.has_facets() && matches!(self.category_order_spec(), CategoryOrder::Value(_)) {
            return Err(Error::Data(
                "value-derived category order is not supported with faceting; each panel can prepare a different value for the same category, so supply an explicit order"
                    .into(),
            ));
        }
        if self.has_facets() {
            self.validate_faceted_explicit_category_orders(kind)?;
        }
        Ok(())
    }

    fn validate_faceted_explicit_category_orders(&self, kind: PlotKind) -> Result<(), Error> {
        let configured_source_rows = self.configured_source_rows()?;
        match kind {
            PlotKind::Bar
            | PlotKind::HorizontalBar
            | PlotKind::StackedBar
            | PlotKind::StackedHorizontalBar => {
                let column = self
                    .x_col()
                    .ok_or_else(|| Error::Data("bar: category column not set".into()))?;
                let crate::data::DataColumn::Category(values) =
                    self.data_column(column).ok_or_else(|| {
                        Error::Data(format!("unknown semantic value {column:?}").into())
                    })?
                else {
                    return Err(Error::Data(
                        format!(
                            "faceted bar category order: value {:?} must be categorical",
                            self.data_column(column).expect("resolved category").name()
                        )
                        .into(),
                    ));
                };
                let observed = crate::data::stable_levels(&strict_source_strings(
                    values,
                    configured_source_rows,
                    "faceted bar category order",
                )?);
                validate_full_explicit_order(
                    self.category_order_spec(),
                    &observed,
                    "bar category order",
                    false,
                )?;
            }
            PlotKind::PointInterval => {
                let column = self
                    .y_col()
                    .ok_or_else(|| Error::Data("point_interval: category column not set".into()))?;
                let crate::data::DataColumn::Category(values) =
                    self.data_column(column).ok_or_else(|| {
                        Error::Data(format!("unknown semantic value {column:?}").into())
                    })?
                else {
                    return Err(Error::Data(
                        format!(
                            "faceted point_interval category order: value {:?} must be categorical",
                            self.data_column(column).expect("resolved category").name()
                        )
                        .into(),
                    ));
                };
                let observed = crate::data::stable_levels(&strict_source_normalized_strings(
                    values,
                    configured_source_rows,
                    "faceted point_interval category order",
                    "category",
                )?);
                validate_full_explicit_order(
                    self.category_order_spec(),
                    &observed,
                    "point_interval category order",
                    true,
                )?;
            }
            PlotKind::Heatmap => {
                self.validate_faceted_heatmap_category_orders(configured_source_rows)?;
            }
            _ => {}
        }
        Ok(())
    }

    fn validate_faceted_heatmap_category_orders(
        &self,
        rows: Option<&crate::data::SourceRows>,
    ) -> Result<(), Error> {
        let x_column = self
            .x_col()
            .ok_or_else(|| Error::Data("heatmap: x category column not set".into()))?;
        let y_column = self
            .y_col()
            .ok_or_else(|| Error::Data("heatmap: y category column not set".into()))?;
        let crate::data::DataColumn::Category(x_values) = self
            .data_column(x_column)
            .ok_or_else(|| Error::Data(format!("unknown semantic value {x_column:?}").into()))?
        else {
            return Err(Error::Data(
                format!(
                    "faceted heatmap category order: value {:?} must be categorical",
                    self.data_column(x_column).expect("resolved x").name()
                )
                .into(),
            ));
        };
        let x_observed = crate::data::stable_levels(&strict_source_normalized_strings(
            x_values,
            rows,
            "faceted heatmap category order",
            "x",
        )?);
        let crate::data::DataColumn::Category(y_values) = self
            .data_column(y_column)
            .ok_or_else(|| Error::Data(format!("unknown semantic value {y_column:?}").into()))?
        else {
            return Err(Error::Data(
                format!(
                    "faceted heatmap category order: value {:?} must be categorical",
                    self.data_column(y_column).expect("resolved y").name()
                )
                .into(),
            ));
        };
        let y_observed = crate::data::stable_levels(&strict_source_normalized_strings(
            y_values,
            rows,
            "faceted heatmap category order",
            "y",
        )?);
        let family = (self.heatmap_layout_spec() != HeatmapLayout::Cartesian).then(|| {
            let mut family = x_observed.clone();
            for level in &y_observed {
                if !family.contains(level) {
                    family.push(level.clone());
                }
            }
            family
        });
        for (axis, observed, order) in [
            (
                "x",
                family.as_deref().unwrap_or(&x_observed),
                self.x_category_order_spec(),
            ),
            (
                "y",
                family.as_deref().unwrap_or(&y_observed),
                self.y_category_order_spec(),
            ),
        ] {
            validate_full_explicit_order(
                order,
                observed,
                &format!("heatmap {axis} category order"),
                true,
            )?;
        }
        if self.heatmap_layout_spec() != HeatmapLayout::Cartesian {
            validate_matching_triangular_orders(
                self.x_category_order_spec(),
                self.y_category_order_spec(),
            )?;
        }
        Ok(())
    }

    pub(crate) fn validate_value_alignment(&self) -> Result<(), Error> {
        use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
        let expected = self.row_count();
        let mismatch = |actual, message, context: ErrorContext| {
            Error::Data(
                Diagnostic::new(
                    DiagnosticKind::ShapeMismatch {
                        expected: vec![expected],
                        actual: vec![actual],
                    },
                    message,
                )
                .with_context(context.with_operation(OperationPhase::Prepare)),
            )
        };
        for values in self.aligned_columns() {
            if values.len() != expected {
                let key = match values {
                    crate::data::DataColumn::Numeric(values) => values.field_key(),
                    crate::data::DataColumn::Category(values) => values.field_key(),
                    crate::data::DataColumn::Boolean(values) => values.field_key(),
                };
                return Err(mismatch(
                    values.len(),
                    format!(
                        "plot value {:?} has length {}, expected {expected}",
                        values.name(),
                        values.len()
                    ),
                    ErrorContext::new().with_binding(
                        key.cloned()
                            .unwrap_or_else(|| crate::data::RawKey::from(values.name())),
                    ),
                ));
            }
        }
        if let Some(statuses) = self.estimate_status_values() {
            if statuses.len() != expected {
                return Err(mismatch(
                    statuses.len(),
                    format!(
                        "plot estimate status values have length {}, expected {expected}",
                        statuses.len()
                    ),
                    ErrorContext::new().with_role(crate::data::DataRole::EstimateStatus),
                ));
            }
        }
        if let Some(rows) = self.source_row_map() {
            if rows.len() != expected {
                return Err(mismatch(
                    rows.len(),
                    format!(
                        "plot source-row map has length {}, expected {expected}",
                        rows.len()
                    ),
                    ErrorContext::new(),
                ));
            }
        }
        Ok(())
    }

    fn validate_facet_configuration(&self) -> Result<(), Error> {
        if self.has_facets() {
            crate::layout::interior::CompositionChildPolicy::Facet.validate_child(self)?;
        }
        if self.has_facets() && !self.panel_text_annotations().is_empty() {
            return Err(Error::Data(
                "panel text annotations are not supported with faceting; each annotation requires one unambiguous chart panel owner"
                    .into(),
            ));
        }
        for annotation in self.significance_annotations() {
            annotation.validate()?;
        }
        if !self.has_facets()
            && self
                .significance_annotations()
                .iter()
                .any(|annotation| annotation.facet_cell().is_some())
        {
            return Err(Error::Render(
                "facet-owned significance annotations require Plot::facet; ownership is never ignored on an unfaceted chart".into(),
            ));
        }
        Ok(())
    }

    pub(crate) fn validate_interval_configuration(&self, kind: PlotKind) -> Result<(), Error> {
        if self.line_band_configured() && kind != PlotKind::Line {
            return Err(Error::Data(
                format!("{kind:?}: band is supported only by Line").into(),
            ));
        }
        if matches!(kind, PlotKind::Bar | PlotKind::HorizontalBar) {
            if self.interval_bound_cols().is_some() {
                return Err(Error::Data(format!(
                    "{kind:?} does not consume line bands; use BarInput::estimates_with_error_bars for precomputed bar bounds"
                ).into()));
            }
            return crate::plots::bar_data::validate_cells(self);
        }
        if matches!(kind, PlotKind::StackedBar | PlotKind::StackedHorizontalBar)
            && self.interval_bound_cols().is_some()
        {
            return Err(Error::Data(
                format!("line bands are not consumed by {kind:?}").into(),
            ));
        }
        if kind != PlotKind::Regression
            && self.regression_band_spec() != RegressionBand::PointwiseMean95
        {
            return Err(Error::Data(
                format!("RegressionBand is supported only by Regression, not {kind:?}").into(),
            ));
        }
        Ok(())
    }

    #[expect(
        clippy::too_many_lines,
        reason = "one exhaustive pre-backend validator covers every typed chart channel"
    )]
    pub(crate) fn validate_channel_configuration(&self, kind: PlotKind) -> Result<(), Error> {
        if !self.panel_text_annotations().is_empty() && kind == PlotKind::Matrix {
            return Err(Error::Data(
                "matrix: panel text annotations require one standard chart panel".into(),
            ));
        }
        if let Some(geometry) = self.histogram_geometry_input() {
            if kind != PlotKind::Histogram {
                return Err(Error::Data(format!(
                    "plot kind {kind:?}: precomputed histogram composite geometry is supported only by Histogram"
                ).into()));
            }
            if self.has_facets() {
                return Err(Error::Data(
                    "histogram: precomputed composite geometry is not supported with faceting"
                        .into(),
                ));
            }
            if self
                .histogram_sample_stat()
                .is_some_and(|stat| stat != geometry.get_bins().bin_stat())
            {
                return Err(Error::Data(
                    "histogram: supplied bin heights cannot change their declared statistic".into(),
                ));
            }
            if self.histogram_bins_spec() != HistogramBins::Auto
                || self.histogram_composite_spec() != &HistogramComposite::HistogramOnly
            {
                return Err(Error::Data(
                    "histogram: precomputed composite geometry cannot be combined with sample-derived HistogramBins or HistogramComposite options"
                        .into(),
                ));
            }
            if self.x_col().is_some()
                || self.y_col().is_some()
                || self.hue_col().is_some()
                || self.group_col().is_some()
            {
                return Err(Error::Data(
                    "histogram: precomputed composite geometry is self-contained and does not accept x, y, hue, or group data channels"
                        .into(),
                ));
            }
            if self.source_row_map().is_some() {
                return Err(Error::Data(
                    "histogram: precomputed composite geometry does not accept source-row inputs"
                        .into(),
                ));
            }
        }
        if self.raincloud_geometry_input().is_some() {
            if kind != PlotKind::Raincloud {
                return Err(Error::Data(format!(
                    "plot kind {kind:?}: precomputed raincloud geometry is supported only by Raincloud"
                ).into()));
            }
            if self.has_facets() {
                return Err(Error::Data(
                    "raincloud: precomputed geometry is not supported with faceting".into(),
                ));
            }
            if self.x_col().is_some()
                || self.y_col().is_some()
                || self.hue_col().is_some()
                || self.group_col().is_some()
            {
                return Err(Error::Data(
                    "raincloud: precomputed geometry is self-contained and does not accept external sample data channels"
                        .into(),
                ));
            }
            if self.source_row_map().is_some() {
                return Err(Error::Data(
                    "raincloud: precomputed geometry does not accept source-row inputs".into(),
                ));
            }
            if !self.significance_annotations().is_empty() {
                return Err(Error::Data(
                    "raincloud: precomputed geometry does not support significance annotations"
                        .into(),
                ));
            }
        }
        if self.histogram_composite_spec().is_enabled() {
            if kind != PlotKind::Histogram {
                return Err(Error::Data(
                    format!(
                        "plot kind {kind:?}: HistogramComposite is supported only by Histogram"
                    )
                    .into(),
                ));
            }
            if self.histogram_stat_spec() != HistogramStat::Density {
                return Err(Error::Data(
                    "histogram: HistogramComposite::KdeAndRug requires HistogramStat::Density so bars and curve share one density axis"
                        .into(),
                ));
            }
        }
        if self.raw_overlay_spec().is_visible()
            && !matches!(kind, PlotKind::Boxplot | PlotKind::Violin)
        {
            return Err(Error::Data(
                format!(
                "plot kind {kind:?}: visible RawOverlay is supported only by Boxplot and Violin"
            )
                .into(),
            ));
        }
        if kind == PlotKind::Trajectory {
            if self.group_col().is_none() {
                return Err(Error::Data(
                    "line trajectory: an explicit graphical group column is required; hue is color-only".into(),
                ));
            }
            self.validate_trajectory_x_axis()?;
        }
        if kind == PlotKind::LinePath {
            self.validate_path_x_axis()?;
        }
        if self.line_path_style_spec() != LinePathStyle::Neutral {
            if kind != PlotKind::LinePath {
                return Err(Error::Data(
                    format!("plot kind {kind:?}: LinePathStyle::Hue is supported only by LinePath")
                        .into(),
                ));
            }
            if self.hue_col().is_none() {
                return Err(Error::Data(
                    "line path: LinePathStyle::Hue requires a categorical hue column".into(),
                ));
            }
        }
        let supports_hue = matches!(
            kind,
            PlotKind::Scatter
                | PlotKind::Density
                | PlotKind::Line
                | PlotKind::Trajectory
                | PlotKind::LinePath
                | PlotKind::Interaction
                | PlotKind::Bar
                | PlotKind::HorizontalBar
                | PlotKind::StackedBar
                | PlotKind::StackedHorizontalBar
                | PlotKind::Boxplot
                | PlotKind::Violin
                | PlotKind::Raincloud
                | PlotKind::Marginal
                | PlotKind::Matrix
        );
        if let Some(column) = self.hue_name().filter(|_| !supports_hue) {
            if kind == PlotKind::Histogram {
                return Err(Error::Data(format!(
                    "histogram: hue column {column:?} is not supported yet; render separate single-series histograms"
                ).into()));
            }
            return Err(Error::Data(
                format!("plot kind {kind:?}: hue column {column:?} is not supported").into(),
            ));
        }
        let supports_group = matches!(
            kind,
            PlotKind::Line
                | PlotKind::Trajectory
                | PlotKind::LinePath
                | PlotKind::Interaction
                | PlotKind::Density
                | PlotKind::Marginal
                | PlotKind::Matrix
                | PlotKind::Bar
                | PlotKind::HorizontalBar
                | PlotKind::StackedBar
                | PlotKind::StackedHorizontalBar
                | PlotKind::Boxplot
                | PlotKind::Violin
                | PlotKind::Raincloud
                | PlotKind::Dumbbell
        );
        if let Some(column) = self.group_col().filter(|_| !supports_group) {
            return Err(Error::Data(
                format!("plot kind {kind:?}: graphical group column {column:?} is not supported")
                    .into(),
            ));
        }
        if matches!(
            kind,
            PlotKind::Trajectory
                | PlotKind::Interaction
                | PlotKind::StackedBar
                | PlotKind::StackedHorizontalBar
        ) && self.group_col().is_none()
        {
            return Err(Error::Data(
                format!("plot kind {kind:?}: an explicit graphical group column is required")
                    .into(),
            ));
        }
        if self.interaction_styles_spec().is_some() {
            if kind != PlotKind::Interaction {
                return Err(Error::Data(
                    format!(
                        "plot kind {kind:?}: interaction styles are supported only by Interaction"
                    )
                    .into(),
                ));
            }
            if !self.markers_visible() {
                return Err(Error::Data(
                    "interaction: configured styles require visible markers".into(),
                ));
            }
        }
        if let Some(connectors) = self.interaction_connectors_spec() {
            if kind != PlotKind::Interaction {
                return Err(Error::Data(
                    format!("plot kind {kind:?}: connectors is supported only by Interaction")
                        .into(),
                ));
            }
            if !connectors && self.interaction_styles_spec().is_some() {
                return Err(Error::Data(
                    "interaction: connectors(false) is incompatible with configured styles".into(),
                ));
            }
        }
        if kind == PlotKind::Interaction
            && !self.markers_visible()
            && !self.interaction_connectors_visible()
        {
            return Err(Error::Data(
                "interaction: markers and connectors cannot both be hidden".into(),
            ));
        }
        if matches!(kind, PlotKind::Boxplot | PlotKind::Violin)
            && self
                .hue_col()
                .is_some_and(|column| Some(column) == self.x_col())
        {
            return Err(Error::Data(format!(
                "plot kind {kind:?}: hue must use a different column from the x category; a redundant hue channel is not silently ignored"
            ).into()));
        }

        let supports_color = matches!(kind, PlotKind::Heatmap | PlotKind::Beeswarm);
        if let Some(column) = self.color_col().filter(|_| !supports_color) {
            return Err(Error::Data(
                format!("plot kind {kind:?}: continuous color column {column:?} is not supported")
                    .into(),
            ));
        }
        if (self.color_label_text().is_some() || self.color_label_format_spec().is_some())
            && self.color_col().is_none()
        {
            return Err(Error::Data(
                format!(
                    "plot kind {kind:?}: a continuous color label requires a numeric color binding"
                )
                .into(),
            ));
        }
        if self.continuous_color_scale_spec().is_some() && self.color_col().is_none() {
            return Err(Error::Data(
                format!(
                    "plot kind {kind:?}: a continuous color scale requires a numeric color binding"
                )
                .into(),
            ));
        }
        if self.highlight_cells_col().is_some() && kind != PlotKind::Heatmap {
            return Err(Error::Data(
                format!("plot kind {kind:?}: a heatmap highlight column is not supported").into(),
            ));
        }
        if self.estimate_labels_spec().is_some() && kind != PlotKind::Coefficient {
            return Err(Error::Data(
                format!(
                    "plot kind {kind:?}: numeric estimate labels are supported only by Coefficient"
                )
                .into(),
            ));
        }
        if self.coefficient_reference_line_value().is_some() && kind != PlotKind::Coefficient {
            return Err(Error::Data(format!(
                "plot kind {kind:?}: reference_line is supported only by Coefficient; Forest receives its reference in Plot::forest"
            ).into()));
        }
        if self.estimate_status_values().is_some()
            && !matches!(
                kind,
                PlotKind::PointInterval | PlotKind::Coefficient | PlotKind::Forest
            )
        {
            return Err(Error::Data(format!(
                "plot kind {kind:?}: estimate status is supported only by PointInterval, Coefficient, and Forest"
            ).into()));
        }
        let supports_bounds = matches!(
            kind,
            PlotKind::PointInterval
                | PlotKind::Line
                | PlotKind::Interaction
                | PlotKind::Coefficient
                | PlotKind::Forest
        );
        if self.interval_bound_cols().is_some() && !supports_bounds {
            return Err(Error::Data(
                format!("plot kind {kind:?}: interval bound columns are not supported").into(),
            ));
        }
        if self.waterfall_labels_spec().is_some() && kind != PlotKind::Waterfall {
            return Err(Error::Data(
                format!(
                "plot kind {kind:?}: waterfall annotation labels are supported only by Waterfall"
            )
                .into(),
            ));
        }
        if kind == PlotKind::Matrix {
            self.validate_matrix_variables()?;
        } else if self
            .matrix_variables()
            .is_some_and(|variables| !variables.is_empty())
        {
            return Err(Error::Data(
                format!("plot kind {kind:?}: matrix variables are not supported").into(),
            ));
        }
        Ok(())
    }

    fn validate_matrix_variables(&self) -> Result<(), Error> {
        if self.x_col().is_some() || self.y_col().is_some() {
            return Err(Error::Data(
                "matrix: x and y channels are not supported; configure only the ordered matrix variable list"
                    .into(),
            ));
        }
        let variables = self.matrix_variables().expect("matrix plot owns variables");
        if variables.len() < 2 {
            return Err(Error::Data(
                "matrix: at least two ordered variables are required".into(),
            ));
        }
        let mut seen = HashSet::new();
        for variable in variables.columns() {
            let variable = variable.raw_name();
            if variable.trim().is_empty() {
                return Err(Error::Data(
                    "matrix: variable names must be nonempty".into(),
                ));
            }
            if !seen.insert(variable) {
                return Err(Error::Data(
                    format!("matrix: duplicate variable name {variable:?}").into(),
                ));
            }
        }
        Ok(())
    }

    fn validate_trajectory_x_axis(&self) -> Result<(), Error> {
        let Some(x_column) = self.x_col() else {
            return Ok(());
        };
        let source = self
            .data_column(x_column)
            .ok_or_else(|| Error::Data(format!("unknown semantic value {x_column:?}").into()))
            .map_err(|error| {
                Error::Data(format!("trajectory: column {x_column:?}: {error}").into())
            })?;
        if source.is_numeric() {
            return Ok(());
        }
        if self.x_axis_spec().window.is_some() {
            return Err(Error::Data(
                "trajectory: categorical condition x does not support numeric x limits".into(),
            ));
        }
        Ok(())
    }

    fn validate_path_x_axis(&self) -> Result<(), Error> {
        let Some(x_column) = self.x_col() else {
            return Ok(());
        };
        let source = self
            .data_column(x_column)
            .ok_or_else(|| Error::Data(format!("unknown semantic value {x_column:?}").into()))
            .map_err(|error| {
                Error::Data(format!("line path: column {x_column:?}: {error}").into())
            })?;
        if source.is_numeric() {
            Ok(())
        } else {
            Err(Error::Data(
                "line path: x must be numeric so source-ordered path geometry remains explicit"
                    .into(),
            ))
        }
    }
}

fn validate_full_explicit_order(
    order: &CategoryOrder,
    observed: &[String],
    context: &str,
    normalize: bool,
) -> Result<(), Error> {
    let CategoryOrder::Explicit(requested) = order else {
        return Ok(());
    };
    let requested = if normalize {
        requested
            .iter()
            .map(|level| crate::data::collapse_whitespace(level))
            .collect::<Vec<_>>()
    } else {
        requested.clone()
    };
    crate::data::explicit_category_order(observed, &requested, context, false)?;
    Ok(())
}

fn validate_matching_triangular_orders(x: &CategoryOrder, y: &CategoryOrder) -> Result<(), Error> {
    let (CategoryOrder::Explicit(x), CategoryOrder::Explicit(y)) = (x, y) else {
        return Ok(());
    };
    let normalized = |levels: &[String]| {
        levels
            .iter()
            .map(|level| crate::data::collapse_whitespace(level))
            .collect::<Vec<_>>()
    };
    if normalized(x) != normalized(y) {
        return Err(Error::Data(
            "heatmap: triangular x and y category orders must resolve to the same family order"
                .into(),
        ));
    }
    Ok(())
}