ruviz 0.7.0

High-performance 2D plotting library for Rust
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
/// Box plot implementation with statistical analysis and outlier detection
use crate::core::plot::PlotBuilder;
use crate::core::style_utils::{StyleResolver, defaults};
use crate::core::{PlottingError, Result};
use crate::data::Data1D;
use crate::plots::traits::{PlotArea, PlotConfig, PlotData, PlotRender};
use crate::render::{Color, LineStyle, MarkerStyle, SkiaRenderer, Theme};

// ===========================================================================
// The category axis, in data units
// ===========================================================================

/// Half the width of one category slot, in data units.
///
/// Bars, box plots, violins and boxen plots share a single categorical x axis:
/// slot *i* is centred on `i` and spans `i ± CATEGORY_SLOT_HALF_WIDTH`, so an
/// axis showing *n* categories runs `-0.5 ..= n - 0.5`.
///
/// The consequence worth relying on is that **every width knob on every one of
/// those plot types is a fraction of one slot** — `BoxPlotConfig::width_ratio`,
/// `ViolinConfig::width` and `BoxenConfig::width` all mean the same thing, and
/// none of them has to know how many categories the figure ended up with.
pub const CATEGORY_SLOT_HALF_WIDTH: f64 = 0.5;

/// The data-space span of the category slot centred on `center`.
///
/// Bounds calculation, tick placement and geometry all go through this, so a
/// plot type cannot be *drawn* in one slot and *measured* in another.
pub fn category_slot_span(center: f64) -> (f64, f64) {
    (
        center - CATEGORY_SLOT_HALF_WIDTH,
        center + CATEGORY_SLOT_HALF_WIDTH,
    )
}

/// One `(tick label, slot centre)` pair per category, in slot order.
///
/// For the plot types whose input *is* a list of category names — bars, strip,
/// swarm — a category's slot is its index. Names shorter than `count` leave the
/// remaining slots unlabelled rather than shifting anything, so a slot always
/// means the same position whether or not it has a name.
pub fn category_slots(names: &[String], count: usize) -> Vec<(String, f64)> {
    (0..count)
        .map(|index| (names.get(index).cloned().unwrap_or_default(), index as f64))
        .collect()
}

/// Configuration for box plots
///
/// Style knobs left as `None` fall back to the crate defaults in
/// [`crate::core::style_utils::defaults`]. Every one of them is resolved into
/// [`BoxPlotData`], which is what renderers read — see the geometry contract
/// documented there.
#[derive(Debug, Clone)]
pub struct BoxPlotConfig {
    /// Method for calculating outliers
    pub outlier_method: OutlierMethod,
    /// Whether to show outliers as individual points
    pub show_outliers: bool,
    /// Whether to show means as additional markers
    pub show_mean: bool,
    /// Box plot orientation
    pub orientation: BoxOrientation,
    /// Whisker calculation method
    pub whisker_method: WhiskerMethod,
    /// Fill alpha (opacity), default from defaults::BOXPLOT_FILL_ALPHA
    pub fill_alpha: Option<f32>,
    /// Edge color (auto-derived from fill if None)
    pub edge_color: Option<Color>,
    /// Edge width in points (default from defaults::PATCH_LINE_WIDTH)
    pub edge_width: Option<f32>,
    /// Box width ratio (fraction of available space, default 0.5)
    pub width_ratio: Option<f32>,
    /// Whisker line width (None = use theme.line_width)
    pub whisker_width: Option<f32>,
    /// Median line width (default: theme.line_width * 1.5)
    pub median_width: Option<f32>,
    /// Cap width as fraction of box width (default 0.5)
    pub cap_width: Option<f32>,
    /// Outlier marker size (default 6.0)
    pub flier_size: Option<f32>,
    /// Category label written under this box on the x axis.
    ///
    /// Set with [`category`](Self::category()). Bars, box plots, violins and
    /// boxen plots share one category axis: slot *i* is centred on `i` and one
    /// data unit wide, so `width_ratio` is a fraction of that slot no matter
    /// how many boxes the figure holds.
    pub category: Option<String>,
    /// Explicit centre on the category axis; `None` claims the next free slot.
    ///
    /// Set with [`x_position`](Self::x_position()).
    pub x_position: Option<f64>,
}

/// Methods for detecting outliers
#[allow(clippy::upper_case_acronyms)] // IQR is the standard statistics acronym
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum OutlierMethod {
    /// Standard IQR method: outliers beyond 1.5 * IQR from quartiles
    #[default]
    IQR,
    /// Modified IQR method: outliers beyond 2.5 * IQR from quartiles
    ModifiedIQR,
    /// Standard deviation method: outliers beyond n standard deviations
    StandardDeviation(f64),
    /// No outlier detection
    None,
}

/// Box plot orientation
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum BoxOrientation {
    /// Vertical box plots
    #[default]
    Vertical,
    /// Horizontal box plots
    Horizontal,
}

/// Methods for calculating whiskers
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum WhiskerMethod {
    /// Whiskers extend to min/max values within 1.5 * IQR from quartiles
    #[default]
    Tukey,
    /// Whiskers extend to actual min/max of data
    MinMax,
    /// Whiskers extend to 5th and 95th percentiles
    Percentile5_95,
    /// Whiskers extend to 10th and 90th percentiles
    Percentile10_90,
}

/// Computed box plot statistics
///
/// # The style fields are the geometry contract
///
/// [`calculate_box_plot`] resolves every optional style knob on
/// [`BoxPlotConfig`] against the crate defaults and stores the concrete value
/// here. [`BoxPlotData::render_styled`] is the reference implementation that
/// consumes them, and **any** backend drawing a box plot must read them from
/// this struct rather than re-deriving constants:
///
/// | Field | Meaning | Default |
/// | --- | --- | --- |
/// | [`x_center`](Self::x_center) | centre of the box's category slot, in data units | `0.0` |
/// | [`width_ratio`](Self::width_ratio) | box width as a fraction of the category slot | `0.5` |
/// | [`cap_width`](Self::cap_width) | whisker cap width as a fraction of the box width | `0.5` |
/// | [`fill_alpha`](Self::fill_alpha) | opacity of the box fill | `0.7` |
/// | [`edge_width`](Self::edge_width) | box outline width, in points | `0.8` |
/// | [`whisker_width`](Self::whisker_width) | whisker/cap stroke width; `None` = `theme.line_width` | `None` |
/// | [`median_width`](Self::median_width) | median stroke width; `None` = `theme.line_width * 1.5` | `None` |
/// | [`flier_size`](Self::flier_size) | outlier marker size | `6.0` |
///
/// A backend that hardcodes `0.3`/`0.6`/`4.0` instead makes the matching
/// setters silent no-ops.
#[derive(Debug, Clone)]
pub struct BoxPlotData {
    /// Minimum value (or lower whisker)
    pub min: f64,
    /// First quartile (Q1, 25th percentile)
    pub q1: f64,
    /// Median (Q2, 50th percentile)
    pub median: f64,
    /// Third quartile (Q3, 75th percentile)
    pub q3: f64,
    /// Maximum value (or upper whisker)
    pub max: f64,
    /// Mean value (optional)
    pub mean: Option<f64>,
    /// Outlier values
    pub outliers: Vec<f64>,
    /// Total number of data points
    pub n_samples: usize,
    /// Interquartile range (Q3 - Q1)
    pub iqr: f64,
    /// Box orientation
    pub orientation: BoxOrientation,
    /// Centre of this box's category slot, in data units.
    ///
    /// Resolved from `BoxPlotConfig::x_position` when the series was added, so
    /// every backend reads the same number instead of each picking its own
    /// "centre of the plot".
    pub x_center: f64,
    /// Fill alpha for box
    pub fill_alpha: f32,
    /// Edge color (None = auto-derive)
    pub edge_color: Option<Color>,
    /// Edge width in points
    pub edge_width: f32,
    /// Box width ratio
    pub width_ratio: f32,
    /// Whisker line width
    pub whisker_width: Option<f32>,
    /// Median line width
    pub median_width: Option<f32>,
    /// Cap width as fraction of box width
    pub cap_width: f32,
    /// Outlier marker size
    pub flier_size: f32,
    /// Whether to show outliers
    pub show_outliers: bool,
    /// Whether to show mean
    pub show_mean: bool,
}

// Implement PlotData trait for BoxPlotData
impl PlotData for BoxPlotData {
    fn data_bounds(&self) -> ((f64, f64), (f64, f64)) {
        // The category axis carries one unit-wide slot per box, centred on
        // `x_center`; the value axis spans the data.
        let (y_min, y_max) = if self.outliers.is_empty() {
            (self.min, self.max)
        } else {
            let outlier_min = self.outliers.iter().copied().fold(f64::INFINITY, f64::min);
            let outlier_max = self
                .outliers
                .iter()
                .copied()
                .fold(f64::NEG_INFINITY, f64::max);
            (self.min.min(outlier_min), self.max.max(outlier_max))
        };

        let slot = category_slot_span(self.x_center);
        match self.orientation {
            BoxOrientation::Vertical => (slot, (y_min, y_max)),
            BoxOrientation::Horizontal => ((y_min, y_max), slot),
        }
    }

    fn is_empty(&self) -> bool {
        self.n_samples == 0
    }
}

// Implement PlotRender trait for BoxPlotData
impl PlotRender for BoxPlotData {
    fn render(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        theme: &Theme,
        color: Color,
    ) -> Result<()> {
        self.render_styled(
            renderer,
            area,
            theme,
            color,
            self.fill_alpha,
            Some(self.edge_width),
        )
    }

    fn render_styled(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        theme: &Theme,
        color: Color,
        alpha: f32,
        line_width: Option<f32>,
    ) -> Result<()> {
        if self.is_empty() {
            return Ok(());
        }

        let resolver = StyleResolver::new(theme);

        // Resolve styling
        let fill_alpha = alpha.clamp(0.0, 1.0);
        let fill_color = color.with_alpha(fill_alpha);
        let edge_color = resolver.edge_color(color, self.edge_color);
        let edge_width = resolver.patch_line_width(line_width);
        let whisker_width = self.whisker_width.unwrap_or(theme.line_width);
        let median_width = self.median_width.unwrap_or(theme.line_width * 1.5);

        // The box sits at the centre of its category slot, wherever that slot
        // ended up — not at "the middle of the plot".
        let center_x = self.x_center;

        match self.orientation {
            BoxOrientation::Vertical => {
                self.render_vertical(
                    renderer,
                    area,
                    center_x,
                    fill_color,
                    edge_color,
                    edge_width,
                    whisker_width,
                    median_width,
                    color,
                )?;
            }
            BoxOrientation::Horizontal => {
                self.render_horizontal(
                    renderer,
                    area,
                    center_x,
                    fill_color,
                    edge_color,
                    edge_width,
                    whisker_width,
                    median_width,
                    color,
                )?;
            }
        }

        Ok(())
    }
}

impl BoxPlotData {
    /// Render a vertical box plot
    fn render_vertical(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        center_x: f64,
        fill_color: Color,
        edge_color: Color,
        edge_width: f32,
        whisker_width: f32,
        median_width: f32,
        marker_color: Color,
    ) -> Result<()> {
        // Widths are fractions of one category slot, which is
        // `2 * CATEGORY_SLOT_HALF_WIDTH` data units across.
        let box_half_width = self.width_ratio as f64 * CATEGORY_SLOT_HALF_WIDTH;
        let cap_half_width = box_half_width * self.cap_width as f64;

        // Convert key y-values to screen coordinates
        let (left_x, _) = area.data_to_screen(center_x - box_half_width, self.q1);
        let (right_x, _) = area.data_to_screen(center_x + box_half_width, self.q1);
        let (_, q1_y) = area.data_to_screen(center_x, self.q1);
        let (_, q3_y) = area.data_to_screen(center_x, self.q3);
        let (_, median_y) = area.data_to_screen(center_x, self.median);
        let (_, min_y) = area.data_to_screen(center_x, self.min);
        let (_, max_y) = area.data_to_screen(center_x, self.max);
        let (center_screen_x, _) = area.data_to_screen(center_x, 0.0);

        // Draw box (filled rectangle from Q1 to Q3)
        let box_x = left_x;
        let box_y = q3_y.min(q1_y); // q3_y is higher on screen (smaller y)
        let box_width = right_x - left_x;
        let box_height = (q1_y - q3_y).abs();

        renderer.draw_rectangle(box_x, box_y, box_width, box_height, fill_color, true)?;

        // Draw box edge
        if edge_width > 0.0 {
            let vertices = [
                (box_x, box_y),
                (box_x + box_width, box_y),
                (box_x + box_width, box_y + box_height),
                (box_x, box_y + box_height),
            ];
            renderer.draw_polygon_outline(&vertices, edge_color, edge_width)?;
        }

        // Draw median line
        renderer.draw_line(
            left_x,
            median_y,
            right_x,
            median_y,
            edge_color,
            median_width,
            LineStyle::Solid,
        )?;

        // Draw whiskers (vertical lines from Q1 to min, and Q3 to max)
        renderer.draw_line(
            center_screen_x,
            q1_y,
            center_screen_x,
            min_y,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;
        renderer.draw_line(
            center_screen_x,
            q3_y,
            center_screen_x,
            max_y,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;

        // Draw caps (horizontal lines at min and max)
        let (cap_left, _) = area.data_to_screen(center_x - cap_half_width, self.min);
        let (cap_right, _) = area.data_to_screen(center_x + cap_half_width, self.min);
        renderer.draw_line(
            cap_left,
            min_y,
            cap_right,
            min_y,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;
        renderer.draw_line(
            cap_left,
            max_y,
            cap_right,
            max_y,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;

        // Draw outliers
        if self.show_outliers && !self.outliers.is_empty() {
            for &outlier in &self.outliers {
                let (ox, oy) = area.data_to_screen(center_x, outlier);
                renderer.draw_marker(ox, oy, self.flier_size, MarkerStyle::Circle, marker_color)?;
            }
        }

        // Draw mean if present
        if self.show_mean
            && let Some(mean_val) = self.mean
        {
            let (mx, my) = area.data_to_screen(center_x, mean_val);
            // Diamond marker for mean
            renderer.draw_marker(mx, my, self.flier_size, MarkerStyle::Diamond, marker_color)?;
        }

        Ok(())
    }

    /// Render a horizontal box plot
    fn render_horizontal(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        center_y: f64,
        fill_color: Color,
        edge_color: Color,
        edge_width: f32,
        whisker_width: f32,
        median_width: f32,
        marker_color: Color,
    ) -> Result<()> {
        // Widths are fractions of one category slot, exactly as in the
        // vertical case — the orientation only decides which axis carries it.
        let box_half_height = self.width_ratio as f64 * CATEGORY_SLOT_HALF_WIDTH;
        let cap_half_height = box_half_height * self.cap_width as f64;

        // Convert key x-values to screen coordinates
        let (q1_x, _) = area.data_to_screen(self.q1, center_y);
        let (q3_x, _) = area.data_to_screen(self.q3, center_y);
        let (median_x, _) = area.data_to_screen(self.median, center_y);
        let (min_x, _) = area.data_to_screen(self.min, center_y);
        let (max_x, _) = area.data_to_screen(self.max, center_y);
        let (_, top_y) = area.data_to_screen(self.q1, center_y - box_half_height);
        let (_, bottom_y) = area.data_to_screen(self.q1, center_y + box_half_height);
        let (_, center_screen_y) = area.data_to_screen(0.0, center_y);

        // Draw box (filled rectangle from Q1 to Q3)
        let box_x = q1_x.min(q3_x);
        let box_y = top_y.min(bottom_y);
        let box_width = (q3_x - q1_x).abs();
        let box_height = (bottom_y - top_y).abs();

        renderer.draw_rectangle(box_x, box_y, box_width, box_height, fill_color, true)?;

        // Draw box edge
        if edge_width > 0.0 {
            let vertices = [
                (box_x, box_y),
                (box_x + box_width, box_y),
                (box_x + box_width, box_y + box_height),
                (box_x, box_y + box_height),
            ];
            renderer.draw_polygon_outline(&vertices, edge_color, edge_width)?;
        }

        // Draw median line (vertical for horizontal box plot)
        renderer.draw_line(
            median_x,
            top_y,
            median_x,
            bottom_y,
            edge_color,
            median_width,
            LineStyle::Solid,
        )?;

        // Draw whiskers (horizontal lines from Q1 to min, and Q3 to max)
        renderer.draw_line(
            q1_x,
            center_screen_y,
            min_x,
            center_screen_y,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;
        renderer.draw_line(
            q3_x,
            center_screen_y,
            max_x,
            center_screen_y,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;

        // Draw caps (vertical lines at min and max)
        let (_, cap_top) = area.data_to_screen(self.min, center_y - cap_half_height);
        let (_, cap_bottom) = area.data_to_screen(self.min, center_y + cap_half_height);
        renderer.draw_line(
            min_x,
            cap_top,
            min_x,
            cap_bottom,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;
        renderer.draw_line(
            max_x,
            cap_top,
            max_x,
            cap_bottom,
            edge_color,
            whisker_width,
            LineStyle::Solid,
        )?;

        // Draw outliers
        if self.show_outliers && !self.outliers.is_empty() {
            for &outlier in &self.outliers {
                let (ox, oy) = area.data_to_screen(outlier, center_y);
                renderer.draw_marker(ox, oy, self.flier_size, MarkerStyle::Circle, marker_color)?;
            }
        }

        // Draw mean if present
        if self.show_mean
            && let Some(mean_val) = self.mean
        {
            let (mx, my) = area.data_to_screen(mean_val, center_y);
            renderer.draw_marker(mx, my, self.flier_size, MarkerStyle::Diamond, marker_color)?;
        }

        Ok(())
    }
}

impl Default for BoxPlotConfig {
    fn default() -> Self {
        Self {
            outlier_method: OutlierMethod::IQR,
            show_outliers: true,
            show_mean: false,
            orientation: BoxOrientation::Vertical,
            whisker_method: WhiskerMethod::Tukey,
            fill_alpha: None,
            edge_color: None,
            edge_width: None,
            width_ratio: None,
            whisker_width: None,
            median_width: None,
            cap_width: None,
            flier_size: None,
            category: None,
            x_position: None,
        }
    }
}

// Implement PlotConfig marker trait
impl PlotConfig for BoxPlotConfig {}

impl BoxPlotConfig {
    pub fn new() -> Self {
        Self::default()
    }

    /// Resolve the box edge against `theme` and the resolved fill colour.
    ///
    /// Returns `(colour, width_in_points)` — the same pair
    /// [`BoxPlotData::render`] strokes the box with, so a legend key cannot
    /// drift from the patch it stands for. `edge_color: None` derives the
    /// colour by darkening the fill; see [`StyleResolver::patch_edge`].
    pub fn resolved_edge(&self, theme: &Theme, fill: Color) -> Option<(Color, f32)> {
        let resolver = StyleResolver::new(theme);
        let width = resolver.patch_line_width(self.edge_width);
        resolver.patch_edge(fill, self.edge_color, width)
    }

    pub fn outlier_method(mut self, method: OutlierMethod) -> Self {
        self.outlier_method = method;
        self
    }

    pub fn show_outliers(mut self, show: bool) -> Self {
        self.show_outliers = show;
        self
    }

    pub fn show_mean(mut self, show: bool) -> Self {
        self.show_mean = show;
        self
    }

    pub fn orientation(mut self, orientation: BoxOrientation) -> Self {
        self.orientation = orientation;
        self
    }

    pub fn whisker_method(mut self, method: WhiskerMethod) -> Self {
        self.whisker_method = method;
        self
    }

    /// Set fill alpha (0.0-1.0)
    pub fn fill_alpha(mut self, alpha: f32) -> Self {
        self.fill_alpha = Some(alpha.clamp(0.0, 1.0));
        self
    }

    /// Set edge color explicitly
    pub fn edge_color(mut self, color: Color) -> Self {
        self.edge_color = Some(color);
        self
    }

    /// Set edge width in points
    pub fn edge_width(mut self, width: f32) -> Self {
        self.edge_width = Some(width);
        self
    }

    /// Set box width ratio (fraction of available space)
    pub fn width_ratio(mut self, ratio: f32) -> Self {
        self.width_ratio = Some(ratio.clamp(0.0, 1.0));
        self
    }

    /// Set whisker line width
    pub fn whisker_width(mut self, width: f32) -> Self {
        self.whisker_width = Some(width);
        self
    }

    /// Set median line width
    pub fn median_width(mut self, width: f32) -> Self {
        self.median_width = Some(width);
        self
    }

    /// Set cap width as fraction of box width
    pub fn cap_width(mut self, width: f32) -> Self {
        self.cap_width = Some(width.clamp(0.0, 1.0));
        self
    }

    /// Set outlier marker size
    pub fn flier_size(mut self, size: f32) -> Self {
        self.flier_size = Some(size);
        self
    }
}

/// Box plot configuration reachable straight from [`Plot::boxplot`].
///
/// [`Plot::boxplot`] returns `PlotBuilder<BoxPlotConfig>`, exactly like the
/// other series methods return their own `PlotBuilder<C>`, so these mirror
/// [`BoxPlotConfig`]'s own setters one for one and can be interleaved freely
/// with the shared styling and plot-level methods on the builder.
///
/// ```rust,no_run
/// use ruviz::prelude::*;
///
/// let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 20.0];
///
/// Plot::new()
///     .boxplot(&data)
///     .show_mean(true)
///     .width_ratio(0.4)
///     .save("boxplot.png")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [`Plot::boxplot`]: crate::core::Plot::boxplot
impl PlotBuilder<BoxPlotConfig> {
    /// Choose how outliers are detected.
    pub fn outlier_method(mut self, method: OutlierMethod) -> Self {
        self.config = std::mem::take(&mut self.config).outlier_method(method);
        self
    }

    /// Show or hide outliers as individual points.
    pub fn show_outliers(mut self, show: bool) -> Self {
        self.config = std::mem::take(&mut self.config).show_outliers(show);
        self
    }

    /// Show or hide the mean marker.
    pub fn show_mean(mut self, show: bool) -> Self {
        self.config = std::mem::take(&mut self.config).show_mean(show);
        self
    }

    /// Set the box orientation.
    pub fn orientation(mut self, orientation: BoxOrientation) -> Self {
        self.config = std::mem::take(&mut self.config).orientation(orientation);
        self
    }

    /// Choose how the whisker ends are calculated.
    pub fn whisker_method(mut self, method: WhiskerMethod) -> Self {
        self.config = std::mem::take(&mut self.config).whisker_method(method);
        self
    }

    /// Set the box fill opacity (0.0-1.0).
    pub fn fill_alpha(mut self, alpha: f32) -> Self {
        self.config = std::mem::take(&mut self.config).fill_alpha(alpha);
        self
    }

    /// Set the box edge colour explicitly.
    pub fn edge_color(mut self, color: Color) -> Self {
        self.config = std::mem::take(&mut self.config).edge_color(color);
        self
    }

    /// Set the box edge width in points.
    pub fn edge_width(mut self, width: f32) -> Self {
        self.config = std::mem::take(&mut self.config).edge_width(width);
        self
    }

    /// Set the box width as a fraction of the available slot.
    pub fn width_ratio(mut self, ratio: f32) -> Self {
        self.config = std::mem::take(&mut self.config).width_ratio(ratio);
        self
    }

    /// Set the whisker line width in points.
    pub fn whisker_width(mut self, width: f32) -> Self {
        self.config = std::mem::take(&mut self.config).whisker_width(width);
        self
    }

    /// Set the median line width in points.
    pub fn median_width(mut self, width: f32) -> Self {
        self.config = std::mem::take(&mut self.config).median_width(width);
        self
    }

    /// Set the whisker cap width as a fraction of the box width.
    pub fn cap_width(mut self, width: f32) -> Self {
        self.config = std::mem::take(&mut self.config).cap_width(width);
        self
    }

    /// Set the outlier marker size in points.
    pub fn flier_size(mut self, size: f32) -> Self {
        self.config = std::mem::take(&mut self.config).flier_size(size);
        self
    }
}

/// Calculate box plot statistics from data
pub fn calculate_box_plot<T, D: Data1D<T>>(data: &D, config: &BoxPlotConfig) -> Result<BoxPlotData>
where
    T: Into<f64> + Copy,
{
    // Collect and validate data using shared utility
    let values = crate::data::collect_finite_values_sorted(data)?;
    let n_samples = values.len();

    // Calculate quartiles
    let q1 = calculate_percentile(&values, 25.0);
    let median = calculate_percentile(&values, 50.0);
    let q3 = calculate_percentile(&values, 75.0);
    let iqr = q3 - q1;

    // Calculate mean if requested
    let mean = if config.show_mean {
        Some(values.iter().sum::<f64>() / n_samples as f64)
    } else {
        None
    };

    // Calculate whiskers and outliers
    let (whisker_min, whisker_max, outliers) =
        calculate_whiskers_and_outliers(&values, q1, q3, iqr, config);

    // Extract styling from config, using defaults for None values
    let fill_alpha = config.fill_alpha.unwrap_or(defaults::BOXPLOT_FILL_ALPHA);
    let edge_color = config.edge_color;
    let edge_width = config.edge_width.unwrap_or(defaults::PATCH_LINE_WIDTH);
    let width_ratio = config.width_ratio.unwrap_or(defaults::BOXPLOT_WIDTH_RATIO);
    let whisker_width = config.whisker_width;
    let median_width = config.median_width;
    let cap_width = config.cap_width.unwrap_or(defaults::BOXPLOT_CAP_WIDTH);
    let flier_size = config.flier_size.unwrap_or(defaults::FLIER_SIZE);

    Ok(BoxPlotData {
        min: whisker_min,
        q1,
        median,
        q3,
        max: whisker_max,
        mean,
        outliers,
        n_samples,
        iqr,
        orientation: config.orientation,
        x_center: config.x_center(),
        fill_alpha,
        edge_color,
        edge_width,
        width_ratio,
        whisker_width,
        median_width,
        cap_width,
        flier_size,
        show_outliers: config.show_outliers,
        show_mean: config.show_mean,
    })
}

// Use shared statistical utilities
use super::statistics::percentile as calculate_percentile;

fn calculate_whiskers_and_outliers(
    values: &[f64],
    q1: f64,
    q3: f64,
    iqr: f64,
    config: &BoxPlotConfig,
) -> (f64, f64, Vec<f64>) {
    let mut outliers = Vec::new();

    // When OutlierMethod::None, whiskers should extend to min/max regardless of whisker_method
    let (whisker_min, whisker_max) = if matches!(config.outlier_method, OutlierMethod::None) {
        (values[0], values[values.len() - 1])
    } else {
        match config.whisker_method {
            WhiskerMethod::Tukey => {
                let lower_bound = q1 - 1.5 * iqr;
                let upper_bound = q3 + 1.5 * iqr;

                // Find whiskers as furthest non-outlier points
                let whisker_min = values
                    .iter()
                    .find(|&&x| x >= lower_bound)
                    .copied()
                    .unwrap_or(values[0]);
                let whisker_max = values
                    .iter()
                    .rev()
                    .find(|&&x| x <= upper_bound)
                    .copied()
                    .unwrap_or(values[values.len() - 1]);

                (whisker_min, whisker_max)
            }
            WhiskerMethod::MinMax => (values[0], values[values.len() - 1]),
            WhiskerMethod::Percentile5_95 => (
                calculate_percentile(values, 5.0),
                calculate_percentile(values, 95.0),
            ),
            WhiskerMethod::Percentile10_90 => (
                calculate_percentile(values, 10.0),
                calculate_percentile(values, 90.0),
            ),
        }
    };

    // Detect outliers based on configuration
    if config.show_outliers {
        let (lower_threshold, upper_threshold) = match config.outlier_method {
            OutlierMethod::IQR => (q1 - 1.5 * iqr, q3 + 1.5 * iqr),
            OutlierMethod::ModifiedIQR => (q1 - 2.5 * iqr, q3 + 2.5 * iqr),
            OutlierMethod::StandardDeviation(n_std) => {
                let mean = values.iter().sum::<f64>() / values.len() as f64;
                let std_dev = (values.iter().map(|x| (x - mean).powi(2)).sum::<f64>()
                    / values.len() as f64)
                    .sqrt();
                (mean - n_std * std_dev, mean + n_std * std_dev)
            }
            OutlierMethod::None => (f64::NEG_INFINITY, f64::INFINITY),
        };

        for &value in values {
            if value < lower_threshold || value > upper_threshold {
                outliers.push(value);
            }
        }
    }

    (whisker_min, whisker_max, outliers)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_box_plot_basic_functionality() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
        let config = BoxPlotConfig::new();

        let result = calculate_box_plot(&data, &config).unwrap();

        assert_eq!(result.n_samples, 10);
        assert_eq!(result.median, 5.5); // Median of 1-10
        assert_eq!(result.q1, 3.25); // Q1
        assert_eq!(result.q3, 7.75); // Q3  
        assert_eq!(result.iqr, 4.5); // Q3 - Q1
        assert!(result.outliers.is_empty()); // No outliers in uniform data
    }

    #[test]
    fn test_box_plot_empty_data() {
        let data: Vec<f64> = vec![];
        let config = BoxPlotConfig::new();

        let result = calculate_box_plot(&data, &config);
        assert!(result.is_err());

        match result.unwrap_err() {
            PlottingError::EmptyDataSet => {}
            _ => panic!("Expected EmptyDataSet error"),
        }
    }

    #[test]
    fn test_box_plot_with_outliers() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 100.0]; // 100 is outlier
        let config = BoxPlotConfig::new();

        let result = calculate_box_plot(&data, &config).unwrap();

        assert_eq!(result.n_samples, 10);
        assert!(!result.outliers.is_empty());
        assert!(result.outliers.contains(&100.0));
        assert!(result.max < 100.0); // Whisker should not extend to outlier
    }

    #[test]
    fn test_box_plot_no_outliers_config() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 100.0]; // 100 would be outlier
        let config = BoxPlotConfig::new().outlier_method(OutlierMethod::None);

        let result = calculate_box_plot(&data, &config).unwrap();

        assert!(result.outliers.is_empty()); // No outliers detected
        assert_eq!(result.max, 100.0); // Max includes extreme value
    }

    #[test]
    fn test_box_plot_with_mean() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let config = BoxPlotConfig::new().show_mean(true);

        let result = calculate_box_plot(&data, &config).unwrap();

        assert!(result.mean.is_some());
        assert_eq!(result.mean.unwrap(), 3.0); // Mean of 1-5
    }

    #[test]
    fn test_box_plot_without_mean() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let config = BoxPlotConfig::new().show_mean(false);

        let result = calculate_box_plot(&data, &config).unwrap();

        assert!(result.mean.is_none());
    }

    #[test]
    fn test_box_plot_single_value() {
        let data = vec![5.0];
        let config = BoxPlotConfig::new();

        let result = calculate_box_plot(&data, &config).unwrap();

        assert_eq!(result.median, 5.0);
        assert_eq!(result.q1, 5.0);
        assert_eq!(result.q3, 5.0);
        assert_eq!(result.min, 5.0);
        assert_eq!(result.max, 5.0);
        assert_eq!(result.iqr, 0.0);
    }

    #[test]
    fn test_box_plot_identical_values() {
        let data = vec![5.0; 100]; // 100 identical values
        let config = BoxPlotConfig::new();

        let result = calculate_box_plot(&data, &config).unwrap();

        assert_eq!(result.median, 5.0);
        assert_eq!(result.q1, 5.0);
        assert_eq!(result.q3, 5.0);
        assert_eq!(result.iqr, 0.0);
        assert!(result.outliers.is_empty());
    }

    #[test]
    fn test_box_plot_whisker_methods() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];

        // Test Tukey method (default)
        let tukey_config = BoxPlotConfig::new().whisker_method(WhiskerMethod::Tukey);
        let tukey_result = calculate_box_plot(&data, &tukey_config).unwrap();

        // Test MinMax method
        let minmax_config = BoxPlotConfig::new().whisker_method(WhiskerMethod::MinMax);
        let minmax_result = calculate_box_plot(&data, &minmax_config).unwrap();

        assert_eq!(minmax_result.min, 1.0);
        assert_eq!(minmax_result.max, 10.0);

        // MinMax whiskers should extend further than or equal to Tukey
        assert!(minmax_result.min <= tukey_result.min);
        assert!(minmax_result.max >= tukey_result.max);
    }

    #[test]
    fn test_box_plot_percentile_whiskers() {
        let data: Vec<f64> = (1..=100).map(|x| x as f64).collect();

        let config = BoxPlotConfig::new().whisker_method(WhiskerMethod::Percentile5_95);
        let result = calculate_box_plot(&data, &config).unwrap();

        // For data 1-100, 5th percentile should be around 5 and 95th around 95
        assert!((result.min - 5.0).abs() < 1.0);
        assert!((result.max - 95.0).abs() < 1.0);
    }

    #[test]
    fn test_box_plot_with_nan_values() {
        let data = vec![1.0, 2.0, f64::NAN, 4.0, 5.0];
        let config = BoxPlotConfig::new();

        let result = calculate_box_plot(&data, &config).unwrap();

        // NaN values should be filtered out
        assert_eq!(result.n_samples, 4); // Only finite values counted
        assert_eq!(result.median, 3.0); // Median of [1,2,4,5] = (2+4)/2 = 3.0
    }

    #[test]
    fn test_box_plot_modified_iqr_outliers() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 15.0]; // 15 might be outlier

        let standard_config = BoxPlotConfig::new().outlier_method(OutlierMethod::IQR);
        let modified_config = BoxPlotConfig::new().outlier_method(OutlierMethod::ModifiedIQR);

        let standard_result = calculate_box_plot(&data, &standard_config).unwrap();
        let modified_result = calculate_box_plot(&data, &modified_config).unwrap();

        // Modified IQR should be more lenient, potentially fewer outliers
        assert!(modified_result.outliers.len() <= standard_result.outliers.len());
    }

    #[test]
    fn test_box_plot_standard_deviation_outliers() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 20.0]; // 20 is outlier
        let config = BoxPlotConfig::new().outlier_method(OutlierMethod::StandardDeviation(2.0));

        let result = calculate_box_plot(&data, &config).unwrap();

        // Should detect outliers beyond 2 standard deviations
        assert!(!result.outliers.is_empty());
    }

    #[test]
    fn test_percentile_calculation() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];

        assert_eq!(calculate_percentile(&data, 0.0), 1.0); // Min
        assert_eq!(calculate_percentile(&data, 50.0), 3.0); // Median
        assert_eq!(calculate_percentile(&data, 100.0), 5.0); // Max
        assert_eq!(calculate_percentile(&data, 25.0), 2.0); // Q1
        assert_eq!(calculate_percentile(&data, 75.0), 4.0); // Q3
    }

    #[test]
    fn test_box_plot_config_builder() {
        let config = BoxPlotConfig::new()
            .outlier_method(OutlierMethod::ModifiedIQR)
            .show_outliers(false)
            .show_mean(true)
            .orientation(BoxOrientation::Horizontal)
            .whisker_method(WhiskerMethod::Percentile10_90);

        match config.outlier_method {
            OutlierMethod::ModifiedIQR => {}
            _ => panic!("Expected ModifiedIQR"),
        }
        assert!(!config.show_outliers);
        assert!(config.show_mean);
        match config.orientation {
            BoxOrientation::Horizontal => {}
            _ => panic!("Expected Horizontal"),
        }
        match config.whisker_method {
            WhiskerMethod::Percentile10_90 => {}
            _ => panic!("Expected Percentile10_90"),
        }
    }

    #[test]
    fn test_plot_data_trait() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
        let config = BoxPlotConfig::new();
        let boxplot = calculate_box_plot(&data, &config).unwrap();

        // Test data_bounds: returns ((x_min, x_max), (y_min, y_max))
        let ((_x_min, _x_max), (y_min, y_max)) = boxplot.data_bounds();
        // Bounds should include y range (min to max whisker values)
        assert!(y_min <= 1.0);
        assert!(y_max >= 10.0);

        // Test is_empty
        assert!(!boxplot.is_empty());
    }

    // ------------------------------------------------------------------
    // The style fields must reach pixels (plan item 2.4)
    //
    // These lock `BoxPlotData::render_styled` — the reference geometry — to the
    // resolved config. A backend that hardcodes its own constants will not be
    // caught here, but it now has an executable spec to match.
    // ------------------------------------------------------------------

    fn render_box(config: &BoxPlotConfig) -> Vec<u8> {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 40.0];
        let boxplot = calculate_box_plot(&data, config).unwrap();
        let theme = Theme::default();
        let mut renderer = SkiaRenderer::new(160, 160, theme.clone()).unwrap();
        // Use the plot's own declared bounds so both orientations get an area
        // that actually contains their geometry.
        let ((x_min, x_max), (y_min, y_max)) = boxplot.data_bounds();
        let area = PlotArea::new(0.0, 0.0, 160.0, 160.0, x_min, x_max, y_min, y_max);
        boxplot
            .render(&mut renderer, &area, &theme, Color::from_rgb(0, 90, 200))
            .unwrap();
        renderer.into_image().pixels
    }

    #[test]
    fn test_every_box_plot_style_field_changes_the_rendered_image() {
        let baseline = render_box(&BoxPlotConfig::new());

        let variants: [(&str, BoxPlotConfig); 8] = [
            ("width_ratio", BoxPlotConfig::new().width_ratio(0.9)),
            ("cap_width", BoxPlotConfig::new().cap_width(0.1)),
            ("fill_alpha", BoxPlotConfig::new().fill_alpha(0.1)),
            (
                "edge_color",
                BoxPlotConfig::new().edge_color(Color::from_rgb(255, 0, 0)),
            ),
            ("edge_width", BoxPlotConfig::new().edge_width(4.0)),
            ("whisker_width", BoxPlotConfig::new().whisker_width(5.0)),
            ("median_width", BoxPlotConfig::new().median_width(6.0)),
            ("flier_size", BoxPlotConfig::new().flier_size(16.0)),
        ];

        for (name, config) in variants {
            assert_ne!(
                baseline,
                render_box(&config),
                "BoxPlotConfig::{name} produced a byte-identical image"
            );
        }
    }

    #[test]
    fn test_box_plot_orientation_changes_the_rendered_image() {
        let vertical = render_box(&BoxPlotConfig::new());
        let horizontal = render_box(&BoxPlotConfig::new().orientation(BoxOrientation::Horizontal));
        assert_ne!(vertical, horizontal);
    }

    #[test]
    fn test_box_plot_defaults_resolve_to_the_documented_constants() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let boxplot = calculate_box_plot(&data, &BoxPlotConfig::new()).unwrap();

        assert_eq!(boxplot.width_ratio, defaults::BOXPLOT_WIDTH_RATIO);
        assert_eq!(boxplot.cap_width, defaults::BOXPLOT_CAP_WIDTH);
        assert_eq!(boxplot.fill_alpha, defaults::BOXPLOT_FILL_ALPHA);
        assert_eq!(boxplot.edge_width, defaults::PATCH_LINE_WIDTH);
        assert_eq!(boxplot.flier_size, defaults::FLIER_SIZE);
        assert_eq!(boxplot.whisker_width, None);
        assert_eq!(boxplot.median_width, None);
    }

    #[test]
    fn test_styling_fields() {
        let config = BoxPlotConfig::new()
            .fill_alpha(0.5)
            .edge_color(Color::from_rgb(255, 0, 0))
            .edge_width(2.0)
            .width_ratio(0.8)
            .whisker_width(1.5)
            .median_width(2.5)
            .cap_width(0.6)
            .flier_size(8.0);

        assert_eq!(config.fill_alpha, Some(0.5));
        assert!(config.edge_color.is_some());
        assert_eq!(config.edge_width, Some(2.0));
        assert_eq!(config.width_ratio, Some(0.8));
        assert_eq!(config.whisker_width, Some(1.5));
        assert_eq!(config.median_width, Some(2.5));
        assert_eq!(config.cap_width, Some(0.6));
        assert_eq!(config.flier_size, Some(8.0));

        // Test that styling propagates to BoxPlotData
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let boxplot = calculate_box_plot(&data, &config).unwrap();

        assert_eq!(boxplot.fill_alpha, 0.5);
        assert!(boxplot.edge_color.is_some());
        assert_eq!(boxplot.edge_width, 2.0);
        assert_eq!(boxplot.width_ratio, 0.8);
    }

    #[test]
    fn test_category_slot_span_is_one_unit_wide() {
        assert_eq!(category_slot_span(0.0), (-0.5, 0.5));
        assert_eq!(category_slot_span(1.0), (0.5, 1.5));
        assert_eq!(category_slot_span(2.0), (1.5, 2.5));
    }

    #[test]
    fn test_slot_position_reaches_the_computed_box() {
        // `.boxplot(&d).category("b")` has to move the box, not just relabel
        // the axis, so the resolved centre travels on `BoxPlotData`.
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];

        let first = calculate_box_plot(&data, &BoxPlotConfig::new()).unwrap();
        assert_eq!(first.x_center, 0.0);
        assert_eq!(first.data_bounds().0, (-0.5, 0.5));

        let second = calculate_box_plot(&data, &BoxPlotConfig::new().x_position(1.0)).unwrap();
        assert_eq!(second.x_center, 1.0);
        assert_eq!(second.data_bounds().0, (0.5, 1.5));
    }

    #[test]
    fn test_horizontal_box_puts_its_slot_on_the_value_free_axis() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let config = BoxPlotConfig::new()
            .orientation(BoxOrientation::Horizontal)
            .x_position(2.0);
        let boxplot = calculate_box_plot(&data, &config).unwrap();

        assert_eq!(boxplot.data_bounds().1, (1.5, 2.5));
    }

    #[test]
    fn test_category_survives_onto_the_config() {
        let config = BoxPlotConfig::new().category("control");
        assert_eq!(config.category.as_deref(), Some("control"));
        // No explicit position: the plot assigns the slot when the series is
        // added, so the config itself still reads as "unplaced".
        assert_eq!(config.x_position, None);
        assert_eq!(config.x_center(), 0.0);
    }
}