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
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
//! Renderable axis: spine, ticks, tick labels, optional grid, and axis label.
//!
//! An [`Axis`] ties together a [`Scale`] (data→scaled mapping), a [`Locator`]
//! (tick positions), and a [`Formatter`] (tick labels) and knows how to draw
//! itself along one edge of an axes rectangle.
//!
//! # Coordinate convention
//!
//! Everything is expressed in a **y-UP** display space measured in pixels: the
//! y axis increases upward, matching the font/path convention used by
//! [`crate::text`]. The raster backend applies its own Y-flip, so callers do
//! not flip here. `axes_bbox` is the axes rectangle in that space.
//!
//! Ticks point **out of** the axes: for a [`AxisSide::Bottom`] axis the spine
//! lies at `y = ymin` and ticks extend downward (decreasing y); for
//! [`AxisSide::Left`] the spine lies at `x = xmin` and ticks extend leftward
//! (decreasing x). [`AxisSide::Top`] and [`AxisSide::Right`] mirror these.
use crate::core::rcparams::TickDirection;
use crate::core::{Affine2D, Bbox, Path, color::Rgba};
use crate::mathtext::{RichText, layout_rich_text};
use crate::render::{GraphicsContext, Renderer};
use crate::text::FontSource;
use crate::axis::scale::{LinearScale, Scale};
use crate::axis::ticker::{AutoLocator, AutoMinorLocator, Formatter, Locator, ScalarFormatter};
/// Which edge of the axes rectangle an [`Axis`] is drawn along.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AxisSide {
/// The bottom edge: spine at `y = ymin`, ticks point downward.
Bottom,
/// The top edge: spine at `y = ymax`, ticks point upward.
Top,
/// The left edge: spine at `x = xmin`, ticks point leftward.
Left,
/// The right edge: spine at `x = xmax`, ticks point rightward.
Right,
}
impl AxisSide {
/// Whether this axis runs horizontally (`Bottom`/`Top`).
fn is_horizontal(self) -> bool {
matches!(self, AxisSide::Bottom | AxisSide::Top)
}
}
/// A renderable axis along one edge of an axes rectangle.
///
/// Construct with [`Axis::new`] and customise via the builder setters. Draw with
/// [`Axis::draw`]. See the [module docs](crate::axis::axis) for the coordinate
/// convention.
pub struct Axis {
/// Which edge the axis is drawn along.
side: AxisSide,
/// The data→scaled coordinate mapping.
scale: Box<dyn Scale>,
/// The tick-position generator.
locator: Box<dyn Locator>,
/// The tick-label generator.
formatter: Box<dyn Formatter>,
/// Optional axis label drawn outside the tick labels.
label: Option<String>,
/// Color used for the spine, ticks, and all text.
color: Rgba,
/// Length of each tick mark, in pixels.
tick_length: f64,
/// Stroke width of the spine and ticks, in pixels.
tick_width: f64,
/// Font size of tick labels, in pixels.
tick_label_size: f64,
/// Font size of the axis label, in pixels.
axis_label_size: f64,
/// Padding between a tick and its label, in pixels.
tick_label_pad: f64,
/// Padding between tick labels and the axis label, in pixels.
axis_label_pad: f64,
/// Whether to draw grid lines spanning the axes at each tick.
grid: bool,
/// Grid line color (before `grid_alpha` is applied).
grid_color: Rgba,
/// Grid line stroke width in pixels.
grid_linewidth: f64,
/// Grid line opacity in `0.0..=1.0`, multiplied into `grid_color`'s alpha.
grid_alpha: f64,
/// Which way tick marks point relative to the spine.
tick_direction: TickDirection,
/// Whether tick labels (and the axis label) are drawn and reserved in
/// layout. Hidden by `sharex` on the inner axes of a stacked pair
/// (matplotlib's `label_outer`); tick marks and the spine stay visible.
tick_labels_visible: bool,
/// The minor-tick locator; `None` draws no minor ticks.
minor_locator: Option<Box<dyn Locator>>,
/// Length of each minor tick mark, in pixels.
minor_tick_length: f64,
/// Stroke width of the minor ticks.
minor_tick_width: f64,
/// Whether to draw grid lines spanning the axes at each minor tick.
minor_grid: bool,
/// Minor grid line color (before `minor_grid_alpha` is applied).
minor_grid_color: Rgba,
/// Minor grid line stroke width.
minor_grid_linewidth: f64,
/// Minor grid line opacity in `0.0..=1.0`.
minor_grid_alpha: f64,
}
/// Snap the fixed coordinate of an axis-aligned stroke to the pixel grid, as
/// matplotlib's `path.snap` does: a line an odd number of pixels wide is
/// centred on a pixel and an even one on a pixel boundary, so a one-pixel
/// line covers one pixel instead of smearing grey over two.
pub(crate) fn snap_to_pixel(coord: f64, width_px: f64) -> f64 {
if !coord.is_finite() {
return coord;
}
if (width_px.round().max(1.0) as i64) % 2 == 1 {
coord.floor() + 0.5
} else {
coord.round()
}
}
/// Default minor tick length (matplotlib's `xtick.minor.size`).
const DEFAULT_MINOR_TICK_LENGTH: f64 = 2.0;
/// Default minor tick width (matplotlib's `xtick.minor.width`).
const DEFAULT_MINOR_TICK_WIDTH: f64 = 0.6;
/// Default grid ink, shared by the major and minor grids.
const DEFAULT_GRID_COLOR: Rgba = Rgba {
r: 0.85,
g: 0.85,
b: 0.85,
a: 1.0,
};
impl Axis {
/// Create an axis for `side` with sensible defaults: a [`LinearScale`], an
/// [`AutoLocator`], a [`ScalarFormatter`], black ink, `tick_length = 3.5`,
/// `tick_width = 1.0`, 10px tick/axis labels, matplotlib-like label pads,
/// and no grid.
#[must_use]
pub fn new(side: AxisSide) -> Self {
Axis {
side,
scale: Box::new(LinearScale::new()),
locator: Box::new(AutoLocator::new()),
formatter: Box::new(ScalarFormatter::new()),
label: None,
color: Rgba::BLACK,
tick_length: 3.5,
tick_width: 1.0,
tick_label_size: 10.0,
axis_label_size: 10.0,
tick_label_pad: 3.5,
axis_label_pad: 4.0,
grid: false,
// 0.85 gray, matching the long-standing hardcoded grid ink.
grid_color: DEFAULT_GRID_COLOR,
grid_linewidth: 1.0,
grid_alpha: 1.0,
tick_direction: TickDirection::Out,
tick_labels_visible: true,
minor_locator: None,
minor_tick_length: DEFAULT_MINOR_TICK_LENGTH,
minor_tick_width: DEFAULT_MINOR_TICK_WIDTH,
minor_grid: false,
minor_grid_color: DEFAULT_GRID_COLOR,
minor_grid_linewidth: 1.0,
minor_grid_alpha: 1.0,
}
}
/// Move the ticks and tick labels of a horizontal axis to the top edge
/// (matplotlib's `xaxis.tick_top()`). Does nothing on a vertical axis.
pub fn tick_top(&mut self) -> &mut Self {
if self.side.is_horizontal() {
self.side = AxisSide::Top;
}
self
}
/// Move the ticks and tick labels of a horizontal axis back to the bottom
/// edge, undoing [`tick_top`](Axis::tick_top). Does nothing on a vertical
/// axis.
pub fn tick_bottom(&mut self) -> &mut Self {
if self.side.is_horizontal() {
self.side = AxisSide::Bottom;
}
self
}
/// Set the major tick length (px at 100 DPI) in place.
pub fn set_tick_length(&mut self, tick_length: f64) -> &mut Self {
self.tick_length = tick_length;
self
}
/// Set the stroke width of the spine and major ticks in place. Widths
/// below one are drawn as given (thin hairlines); zero hides them.
pub fn set_tick_width(&mut self, tick_width: f64) -> &mut Self {
self.tick_width = tick_width;
self
}
/// Set the tick label font size (px at 100 DPI) in place.
pub fn set_tick_label_size(&mut self, tick_label_size: f64) -> &mut Self {
self.tick_label_size = tick_label_size;
self
}
/// Set the padding between a tick and its label (px at 100 DPI) in place.
pub fn set_tick_label_pad(&mut self, tick_label_pad: f64) -> &mut Self {
self.tick_label_pad = tick_label_pad;
self
}
/// Place minor ticks with `locator` (matplotlib's
/// `set_minor_locator`). An [`AutoMinorLocator`] subdivides this axis'
/// actual major ticks, including fixed ones.
///
/// [`AutoMinorLocator`]: crate::axis::ticker::AutoMinorLocator
pub fn set_minor_locator(&mut self, locator: Box<dyn Locator>) -> &mut Self {
self.minor_locator = Some(locator);
self
}
/// Turn on automatic minor ticks between the major ticks (matplotlib's
/// `minorticks_on`): an [`AutoMinorLocator`] with matplotlib's
/// subdivision choice.
///
/// [`AutoMinorLocator`]: crate::axis::ticker::AutoMinorLocator
pub fn minorticks_on(&mut self) -> &mut Self {
self.set_minor_locator(Box::new(AutoMinorLocator::new()))
}
/// Remove the minor ticks (and so the minor grid).
pub fn minorticks_off(&mut self) -> &mut Self {
self.minor_locator = None;
self
}
/// Set the minor tick length (px at 100 DPI) and stroke width in place.
pub fn set_minor_tick_params(&mut self, length: f64, width: f64) -> &mut Self {
self.minor_tick_length = length;
self.minor_tick_width = width;
self
}
/// Enable or disable grid lines at the minor ticks (matplotlib's
/// `grid(which="minor")`). Draws nothing until minor ticks are on.
pub fn set_minor_grid(&mut self, grid: bool) -> &mut Self {
self.minor_grid = grid;
self
}
/// Set the minor grid line color, width, and opacity (`0.0..=1.0`) in
/// place.
pub fn set_minor_grid_style(&mut self, color: Rgba, linewidth: f64, alpha: f64) -> &mut Self {
self.minor_grid_color = color;
self.minor_grid_linewidth = linewidth;
self.minor_grid_alpha = alpha;
self
}
/// Show or hide the tick labels and axis label (tick marks and the spine
/// always draw). Hidden labels also stop reserving layout room.
pub fn set_tick_labels_visible(&mut self, visible: bool) -> &mut Self {
self.tick_labels_visible = visible;
self
}
/// Which edge this axis is drawn along.
#[must_use]
pub fn side(&self) -> AxisSide {
self.side
}
/// The ink color of the spine, ticks, and text.
#[must_use]
pub fn color(&self) -> Rgba {
self.color
}
/// Which way tick marks currently point.
#[must_use]
pub fn tick_direction(&self) -> TickDirection {
self.tick_direction
}
/// Set the scale, returning `self` for chaining.
#[must_use]
pub fn with_scale(mut self, scale: Box<dyn Scale>) -> Self {
self.scale = scale;
self
}
/// Replace the scale in-place.
pub fn set_scale(&mut self, scale: Box<dyn Scale>) -> &mut Self {
self.scale = scale;
self
}
/// Set the locator, returning `self` for chaining.
#[must_use]
pub fn with_locator(mut self, locator: Box<dyn Locator>) -> Self {
self.locator = locator;
self
}
/// Replace the tick locator in-place.
pub fn set_locator(&mut self, locator: Box<dyn Locator>) -> &mut Self {
self.locator = locator;
self
}
/// Set the formatter, returning `self` for chaining.
#[must_use]
pub fn with_formatter(mut self, formatter: Box<dyn Formatter>) -> Self {
self.formatter = formatter;
self
}
/// Replace the tick formatter in-place.
pub fn set_formatter(&mut self, formatter: Box<dyn Formatter>) -> &mut Self {
self.formatter = formatter;
self
}
/// Set the axis label, returning `self` for chaining.
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
/// Set the ink color, returning `self` for chaining.
#[must_use]
pub fn with_color(mut self, color: Rgba) -> Self {
self.color = color;
self
}
/// Set the tick length in pixels, returning `self` for chaining.
#[must_use]
pub fn with_tick_length(mut self, tick_length: f64) -> Self {
self.tick_length = tick_length;
self
}
/// Set the spine/tick stroke width in pixels, returning `self` for chaining.
#[must_use]
pub fn with_tick_width(mut self, tick_width: f64) -> Self {
self.tick_width = tick_width;
self
}
/// Set tick-label and axis-label font sizes in pixels, returning `self`
/// for chaining.
#[must_use]
pub fn with_label_size(mut self, label_size: f64) -> Self {
self.tick_label_size = label_size;
self.axis_label_size = label_size;
self
}
/// Set the tick-label font size in pixels, returning `self` for chaining.
#[must_use]
pub fn with_tick_label_size(mut self, tick_label_size: f64) -> Self {
self.tick_label_size = tick_label_size;
self
}
/// Set the axis-label font size in pixels, returning `self` for chaining.
#[must_use]
pub fn with_axis_label_size(mut self, axis_label_size: f64) -> Self {
self.axis_label_size = axis_label_size;
self
}
/// Set tick-to-label and tick-label-to-axis-label padding in pixels,
/// returning `self` for chaining.
#[must_use]
pub fn with_label_pad(mut self, label_pad: f64) -> Self {
self.tick_label_pad = label_pad;
self.axis_label_pad = label_pad;
self
}
/// Set the tick-to-label padding in pixels, returning `self` for chaining.
#[must_use]
pub fn with_tick_label_pad(mut self, tick_label_pad: f64) -> Self {
self.tick_label_pad = tick_label_pad;
self
}
/// Set the tick-label-to-axis-label padding in pixels, returning `self`
/// for chaining.
#[must_use]
pub fn with_axis_label_pad(mut self, axis_label_pad: f64) -> Self {
self.axis_label_pad = axis_label_pad;
self
}
/// Enable or disable grid lines, returning `self` for chaining.
#[must_use]
pub fn with_grid(mut self, grid: bool) -> Self {
self.grid = grid;
self
}
/// Set the ink color (spine, ticks, and text) in place.
pub fn set_color(&mut self, color: Rgba) -> &mut Self {
self.color = color;
self
}
/// Enable or disable grid lines in place.
pub fn set_grid(&mut self, grid: bool) -> &mut Self {
self.grid = grid;
self
}
/// Set the grid line color, width (px), and opacity (`0.0..=1.0`) in place.
pub fn set_grid_style(&mut self, color: Rgba, linewidth: f64, alpha: f64) -> &mut Self {
self.grid_color = color;
self.grid_linewidth = linewidth;
self.grid_alpha = alpha;
self
}
/// Set which way tick marks point relative to the spine, returning `self`
/// for chaining.
#[must_use]
pub fn with_tick_direction(mut self, direction: TickDirection) -> Self {
self.tick_direction = direction;
self
}
/// Set the tick-mark direction in place.
pub fn set_tick_direction(&mut self, direction: TickDirection) -> &mut Self {
self.tick_direction = direction;
self
}
/// Map a data value to its pixel position along the axis dimension.
///
/// Uses the scale's forward transform, then linearly interpolates the
/// transformed fraction across the relevant axes-rectangle extent. For
/// `Bottom`/`Top` the result is an x coordinate; for `Left`/`Right` it is a
/// y coordinate. A degenerate (zero-width) scaled range collapses to the
/// low edge.
fn data_to_pixel(&self, v: f64, axes_bbox: &Bbox, vmin: f64, vmax: f64) -> f64 {
let tmin = self.scale.transform(vmin);
let tmax = self.scale.transform(vmax);
let denom = tmax - tmin;
let frac = if denom == 0.0 {
0.0
} else {
(self.scale.transform(v) - tmin) / denom
};
let (lo, hi) = if self.side.is_horizontal() {
(axes_bbox.xmin(), axes_bbox.xmax())
} else {
(axes_bbox.ymin(), axes_bbox.ymax())
};
lo + frac * (hi - lo)
}
/// Draw the axis into `renderer`.
///
/// `axes_bbox` is the axes rectangle in y-UP pixel space, `data_lim` is the
/// `(vmin, vmax)` data range mapped across the axis, and `font` supplies the
/// glyph outlines for tick and axis labels.
///
/// Drawing order is grid (if enabled) first, then spine, ticks, tick
/// labels, and finally the axis label, so later strokes sit atop the grid.
pub fn draw(
&self,
renderer: &mut dyn Renderer,
axes_bbox: &Bbox,
data_lim: (f64, f64),
font: &FontSource,
) {
let (vmin, vmax) = data_lim;
let (ticks, labels) = self.visible_ticks(data_lim);
let minor_ticks = self.visible_minor_ticks(data_lim);
// Widths are drawn as given, so sub-unit hairlines stay thin; a
// non-positive width draws nothing.
let stroke_gc = GraphicsContext::new()
.with_stroke(self.color)
.with_line_width(self.tick_width);
let minor_gc = GraphicsContext::new()
.with_stroke(self.color)
.with_line_width(self.minor_tick_width);
if self.minor_grid {
let style = (
self.minor_grid_color,
self.minor_grid_linewidth,
self.minor_grid_alpha,
);
self.draw_grid(renderer, axes_bbox, &minor_ticks, (vmin, vmax), style);
}
if self.grid {
let style = (self.grid_color, self.grid_linewidth, self.grid_alpha);
self.draw_grid(renderer, axes_bbox, &ticks, (vmin, vmax), style);
}
// Decoration geometry (ticks, label sizes, pads) is authored in px at
// the default 100 DPI and scales with the renderer's DPI.
let s = renderer.decoration_scale();
if self.tick_width > 0.0 {
self.draw_spine(renderer, axes_bbox, &stroke_gc);
let length = self.tick_length * s;
self.draw_ticks(
renderer,
axes_bbox,
&ticks,
(vmin, vmax),
&stroke_gc,
length,
);
}
if self.minor_tick_width > 0.0 {
let length = self.minor_tick_length * s;
self.draw_ticks(
renderer,
axes_bbox,
&minor_ticks,
(vmin, vmax),
&minor_gc,
length,
);
}
if self.tick_labels_visible {
self.draw_tick_labels(renderer, axes_bbox, &ticks, &labels, (vmin, vmax), font, s);
self.draw_axis_label(renderer, axes_bbox, &labels, font, s);
}
}
/// The major ticks within `lim` paired with their labels.
///
/// The locator runs over the full limits and the formatter labels *every*
/// location it returns before out-of-range ticks are dropped, so a
/// position-indexed formatter such as
/// [`FixedFormatter`](crate::axis::ticker::FixedFormatter) pairs label `i`
/// with the locator's `i`-th position regardless of which positions are
/// currently in view. This is the order matplotlib's `Axis._update_ticks`
/// uses (format, then clip to the view interval).
pub(crate) fn visible_ticks(&self, lim: (f64, f64)) -> (Vec<f64>, Vec<String>) {
let (vmin, vmax) = lim;
let (lo_v, hi_v) = if vmin <= vmax {
(vmin, vmax)
} else {
(vmax, vmin)
};
let all = self.locator.tick_values(vmin, vmax);
let labels = self.formatter.format_ticks(&all);
all.into_iter()
.zip(labels)
.filter(|&(t, _)| t >= lo_v && t <= hi_v)
.unzip()
}
/// The minor ticks within `lim`, excluding any that coincide with a major
/// tick. Empty when no minor locator is set.
pub(crate) fn visible_minor_ticks(&self, lim: (f64, f64)) -> Vec<f64> {
let Some(minor) = &self.minor_locator else {
return Vec::new();
};
let (vmin, vmax) = lim;
let (lo_v, hi_v) = if vmin <= vmax {
(vmin, vmax)
} else {
(vmax, vmin)
};
let major = self.locator.tick_values(vmin, vmax);
let tolerance = (hi_v - lo_v).abs() * 1e-9;
minor
.minor_tick_values(&major, vmin, vmax)
.into_iter()
.filter(|&t| t >= lo_v && t <= hi_v)
.filter(|&t| major.iter().all(|&m| (m - t).abs() > tolerance))
.collect()
}
/// The outward length of the longest drawn tick mark, unscaled.
fn outward_tick_length(&self) -> f64 {
if self.minor_locator.is_some() {
self.tick_length.max(self.minor_tick_length)
} else {
self.tick_length
}
}
/// The outward extent, in pixels, this axis' decoration (ticks, tick
/// labels, and the axis label) occupies beyond the frame edge, for limits
/// `lim` at decoration scale `s`. Drives tight layout: the frame is inset
/// from its envelope by exactly this much per side (plus a pad).
pub(crate) fn decoration_extent(&self, lim: (f64, f64), font: &FontSource, s: f64) -> f64 {
if !self.tick_labels_visible {
// Only the outward tick marks occupy space.
return self.outward_tick_length() * s;
}
let (_, labels) = self.visible_ticks(lim);
let mut extent = (self.tick_length + self.tick_label_pad) * s
+ self.tick_label_band_extent(&labels, font, s);
if let Some(label) = self.label.as_ref().filter(|label| !label.is_empty()) {
let rich = layout_rich_text(font, label, self.axis_label_size * s);
// The axis label sits past the tick labels by axis_label_pad; its
// occupied thickness is its line height (width when the label is
// rotated along a vertical axis, but height bounds both since the
// rotated label's *thickness* is still one line).
extent += self.axis_label_pad * s + rich.ascent + rich.descent;
}
extent
}
/// The half-size overhang of the outermost tick labels past the two ends
/// of the axis span, `(low_end, high_end)`, in pixels at decoration scale
/// `s`.
///
/// Tick labels are centered on their ticks, so a tick sitting at an axis
/// limit spills half its label beyond the frame corner — half its width
/// along a horizontal axis, half its height along a vertical one.
/// matplotlib's tight layout reserves this room by measuring the axes
/// tight bbox; this is the measured equivalent. Only ticks within 2% of
/// an end can overhang it.
pub(crate) fn end_label_overhangs(
&self,
lim: (f64, f64),
font: &FontSource,
s: f64,
) -> (f64, f64) {
if !self.tick_labels_visible {
return (0.0, 0.0);
}
let (vmin, vmax) = lim;
let (lo_v, hi_v) = if vmin <= vmax {
(vmin, vmax)
} else {
(vmax, vmin)
};
let span = hi_v - lo_v;
if !span.is_finite() || span <= 0.0 {
return (0.0, 0.0);
}
let (ticks, labels) = self.visible_ticks(lim);
let (mut low, mut high) = (0.0f64, 0.0f64);
for (&t, label) in ticks.iter().zip(&labels) {
if label.is_empty() {
continue;
}
let frac = (t - lo_v) / span;
if frac > 0.02 && frac < 0.98 {
continue;
}
let rich = layout_rich_text(font, label, self.tick_label_size * s);
let half = if self.side.is_horizontal() {
rich.width / 2.0
} else {
(rich.ascent + rich.descent) / 2.0
};
if frac <= 0.02 {
low = low.max(half);
} else {
high = high.max(half);
}
}
(low, high)
}
/// Stroke the spine along the relevant edge.
fn draw_spine(&self, renderer: &mut dyn Renderer, axes_bbox: &Bbox, gc: &GraphicsContext) {
let (xmin, xmax) = (axes_bbox.xmin(), axes_bbox.xmax());
let (ymin, ymax) = (axes_bbox.ymin(), axes_bbox.ymax());
let snap = |c| snap_to_pixel(c, renderer.points_to_pixels(gc.line_width));
let line = match self.side {
AxisSide::Bottom => [[xmin, snap(ymin)], [xmax, snap(ymin)]],
AxisSide::Top => [[xmin, snap(ymax)], [xmax, snap(ymax)]],
AxisSide::Left => [[snap(xmin), ymin], [snap(xmin), ymax]],
AxisSide::Right => [[snap(xmax), ymin], [snap(xmax), ymax]],
};
let path = Path::from_polyline(&line);
renderer.draw_path(gc, &path, &Affine2D::identity(), None);
}
/// Stroke grid lines spanning the axes, one per tick, in the given
/// `(color, linewidth, alpha)` style.
fn draw_grid(
&self,
renderer: &mut dyn Renderer,
axes_bbox: &Bbox,
ticks: &[f64],
(vmin, vmax): (f64, f64),
(color, linewidth, alpha): (Rgba, f64, f64),
) {
if linewidth <= 0.0 {
return;
}
let alpha = alpha.clamp(0.0, 1.0);
let stroke = color.with_alpha(color.a * alpha);
let gc = GraphicsContext::new()
.with_stroke(stroke)
.with_line_width(linewidth);
let (xmin, xmax) = (axes_bbox.xmin(), axes_bbox.xmax());
let (ymin, ymax) = (axes_bbox.ymin(), axes_bbox.ymax());
let width_px = renderer.points_to_pixels(linewidth);
for &t in ticks {
let p = snap_to_pixel(self.data_to_pixel(t, axes_bbox, vmin, vmax), width_px);
let line = if self.side.is_horizontal() {
[[p, ymin], [p, ymax]]
} else {
[[xmin, p], [xmax, p]]
};
let path = Path::from_polyline(&line);
renderer.draw_path(&gc, &path, &Affine2D::identity(), None);
}
}
/// Stroke a tick mark of (scaled) length `len` in the tick direction at
/// each tick position.
fn draw_ticks(
&self,
renderer: &mut dyn Renderer,
axes_bbox: &Bbox,
ticks: &[f64],
lim: (f64, f64),
gc: &GraphicsContext,
len: f64,
) {
let (vmin, vmax) = lim;
// Outward and inward extents relative to the spine, per direction.
let (out_len, in_len) = match self.tick_direction {
TickDirection::Out => (len, 0.0),
TickDirection::In => (0.0, len),
TickDirection::InOut => (len, len),
};
let width_px = renderer.points_to_pixels(gc.line_width);
for &t in ticks {
let p = snap_to_pixel(self.data_to_pixel(t, axes_bbox, vmin, vmax), width_px);
// `edge` is the spine coordinate; `out`/`in` sign points away from /
// into the axes for this side.
let (edge, out_sign) = match self.side {
AxisSide::Bottom => (axes_bbox.ymin(), -1.0),
AxisSide::Top => (axes_bbox.ymax(), 1.0),
AxisSide::Left => (axes_bbox.xmin(), -1.0),
AxisSide::Right => (axes_bbox.xmax(), 1.0),
};
let far = edge + out_sign * out_len;
let near = edge - out_sign * in_len;
let line = if self.side.is_horizontal() {
[[p, near], [p, far]]
} else {
[[near, p], [far, p]]
};
let path = Path::from_polyline(&line);
renderer.draw_path(gc, &path, &Affine2D::identity(), None);
}
}
/// Fill each tick label just outside its tick, centered on the tick.
/// Draw one label per tick; `labels` is index-aligned with `ticks` (see
/// [`Axis::visible_ticks`]) and empty strings are skipped.
#[allow(clippy::too_many_arguments)]
fn draw_tick_labels(
&self,
renderer: &mut dyn Renderer,
axes_bbox: &Bbox,
ticks: &[f64],
labels: &[String],
lim: (f64, f64),
font: &FontSource,
s: f64,
) {
let (vmin, vmax) = lim;
let gc = GraphicsContext::new();
for (&t, text) in ticks.iter().zip(labels.iter()) {
if text.is_empty() {
continue;
}
let rich = layout_rich_text(font, text, self.tick_label_size * s);
let p = self.data_to_pixel(t, axes_bbox, vmin, vmax);
let origin = self.tick_label_origin(axes_bbox, p, &rich, s);
let shift = Affine2D::from_translation(origin[0], origin[1]);
for path in &rich.paths {
renderer.draw_path(
&gc,
&path.transformed(&shift),
&Affine2D::identity(),
Some(self.color),
);
}
}
}
/// Compute the baseline origin `(x, y)` for a tick label centered on the
/// tick position `p` and offset out of the axes by `tick_label_pad`.
fn tick_label_origin(&self, axes_bbox: &Bbox, p: f64, rich: &RichText, s: f64) -> [f64; 2] {
let out = (self.tick_length + self.tick_label_pad) * s;
match self.side {
AxisSide::Bottom => {
let x = p - rich.width / 2.0;
let y = axes_bbox.ymin() - out - rich.ascent;
[x, y]
}
AxisSide::Top => {
let x = p - rich.width / 2.0;
let y = axes_bbox.ymax() + out + rich.descent;
[x, y]
}
AxisSide::Left => {
// Left of the tick: right-align the text to the offset point.
let x = axes_bbox.xmin() - out - rich.width;
let y = p - (rich.ascent - rich.descent) / 2.0;
[x, y]
}
AxisSide::Right => {
let x = axes_bbox.xmax() + out;
let y = p - (rich.ascent - rich.descent) / 2.0;
[x, y]
}
}
}
/// The thickness of the tick-label band: the tallest label along a
/// horizontal axis, the widest along a vertical one.
fn tick_label_band_extent(&self, labels: &[String], font: &FontSource, s: f64) -> f64 {
labels
.iter()
.filter(|label| !label.is_empty())
.map(|label| {
let rich = layout_rich_text(font, label, self.tick_label_size * s);
if self.side.is_horizontal() {
rich.ascent + rich.descent
} else {
rich.width
}
})
.fold(0.0, f64::max)
}
/// Fill the axis label (if any), centered along the axis and offset further
/// out than the tick labels.
fn draw_axis_label(
&self,
renderer: &mut dyn Renderer,
axes_bbox: &Bbox,
tick_labels: &[String],
font: &FontSource,
s: f64,
) {
let Some(label) = &self.label else {
return;
};
if label.is_empty() {
return;
}
let gc = GraphicsContext::new();
let rich = layout_rich_text(font, label, self.axis_label_size * s);
let tick_label_extent = self.tick_label_band_extent(tick_labels, font, s);
let label_offset =
(self.tick_length + self.tick_label_pad + self.axis_label_pad) * s + tick_label_extent;
let transform = match self.side {
AxisSide::Bottom => {
let x = (axes_bbox.xmin() + axes_bbox.xmax()) / 2.0 - rich.width / 2.0;
let y = axes_bbox.ymin() - label_offset - rich.ascent;
Affine2D::from_translation(x, y)
}
AxisSide::Top => {
let x = (axes_bbox.xmin() + axes_bbox.xmax()) / 2.0 - rich.width / 2.0;
let y = axes_bbox.ymax() + label_offset + rich.descent;
Affine2D::from_translation(x, y)
}
AxisSide::Left => {
let right = axes_bbox.xmin() - label_offset;
let x = right - rich.descent;
let y = (axes_bbox.ymin() + axes_bbox.ymax()) / 2.0 - rich.width / 2.0;
Affine2D::from_rotation_deg(90.0).then(&Affine2D::from_translation(x, y))
}
AxisSide::Right => {
let left = axes_bbox.xmax() + label_offset;
let x = left + rich.descent;
let y = (axes_bbox.ymin() + axes_bbox.ymax()) / 2.0 + rich.width / 2.0;
Affine2D::from_rotation_deg(-90.0).then(&Affine2D::from_translation(x, y))
}
};
for path in &rich.paths {
renderer.draw_path(
&gc,
&path.transformed(&transform),
&Affine2D::identity(),
Some(self.color),
);
}
}
}
#[cfg(feature = "portable")]
impl Axis {
/// Flatten this axis into its wire form for portable-figure export.
///
/// Fails loudly when the scale, locator, or formatter has no wire
/// representation (a [`FuncFormatter`](crate::axis::ticker::FuncFormatter)
/// closure, or a third-party trait implementation).
pub(crate) fn to_portable(
&self,
) -> Result<crate::portable::spec::AxisSpec, crate::portable::PortableError> {
use crate::portable::PortableError;
Ok(crate::portable::spec::AxisSpec {
side: self.side,
scale: self
.scale
.portable_spec()
.ok_or_else(|| {
PortableError::Unsupported("axis scale has no portable wire form".to_string())
})?
.0,
locator: self
.locator
.portable_spec()
.ok_or_else(|| {
PortableError::Unsupported("axis locator has no portable wire form".to_string())
})?
.0,
formatter: self
.formatter
.portable_spec()
.ok_or_else(|| {
PortableError::Unsupported(
"axis formatter has no portable wire form (FuncFormatter closures \
cannot be exported)"
.to_string(),
)
})?
.0,
label: self.label.clone(),
color: self.color,
tick_length: self.tick_length,
tick_width: self.tick_width,
tick_label_size: self.tick_label_size,
axis_label_size: self.axis_label_size,
tick_label_pad: self.tick_label_pad,
axis_label_pad: self.axis_label_pad,
grid: self.grid,
grid_color: self.grid_color,
grid_linewidth: self.grid_linewidth,
grid_alpha: self.grid_alpha,
tick_direction: self.tick_direction,
tick_labels_visible: self.tick_labels_visible,
minor: self.minor_to_portable()?,
})
}
/// The minor-tick wire form, or `None` while every minor setting is at
/// its default so artifacts that never use minor ticks stay unchanged.
fn minor_to_portable(
&self,
) -> Result<Option<crate::portable::spec::MinorAxisSpec>, crate::portable::PortableError> {
let locator = match &self.minor_locator {
Some(locator) => Some(
locator
.portable_spec()
.ok_or_else(|| {
crate::portable::PortableError::Unsupported(
"axis minor locator has no portable wire form".to_string(),
)
})?
.0,
),
None => None,
};
let spec = crate::portable::spec::MinorAxisSpec {
locator,
tick_length: self.minor_tick_length,
tick_width: self.minor_tick_width,
grid: self.minor_grid,
grid_color: self.minor_grid_color,
grid_linewidth: self.minor_grid_linewidth,
grid_alpha: self.minor_grid_alpha,
};
let default = Axis::new(self.side);
let unchanged = spec.locator.is_none()
&& spec.tick_length == default.minor_tick_length
&& spec.tick_width == default.minor_tick_width
&& spec.grid == default.minor_grid
&& spec.grid_color == default.minor_grid_color
&& spec.grid_linewidth == default.minor_grid_linewidth
&& spec.grid_alpha == default.minor_grid_alpha;
Ok((!unchanged).then_some(spec))
}
/// Reconstruct an axis from its wire form during portable-figure import.
pub(crate) fn from_portable(
spec: &crate::portable::spec::AxisSpec,
) -> Result<Axis, crate::portable::PortableError> {
Axis {
side: spec.side,
scale: spec.scale.into_scale(),
locator: spec.locator.clone().into_locator()?,
formatter: spec.formatter.clone().into_formatter(),
label: spec.label.clone(),
color: spec.color,
tick_length: spec.tick_length,
tick_width: spec.tick_width,
tick_label_size: spec.tick_label_size,
axis_label_size: spec.axis_label_size,
tick_label_pad: spec.tick_label_pad,
axis_label_pad: spec.axis_label_pad,
grid: spec.grid,
grid_color: spec.grid_color,
grid_linewidth: spec.grid_linewidth,
grid_alpha: spec.grid_alpha,
tick_direction: spec.tick_direction,
tick_labels_visible: spec.tick_labels_visible,
minor_locator: None,
minor_tick_length: DEFAULT_MINOR_TICK_LENGTH,
minor_tick_width: DEFAULT_MINOR_TICK_WIDTH,
minor_grid: false,
minor_grid_color: DEFAULT_GRID_COLOR,
minor_grid_linewidth: 1.0,
minor_grid_alpha: 1.0,
}
.with_portable_minor(spec.minor.as_ref())
}
/// Apply a decoded minor-tick wire form, if the artifact carried one.
fn with_portable_minor(
mut self,
minor: Option<&crate::portable::spec::MinorAxisSpec>,
) -> Result<Axis, crate::portable::PortableError> {
if let Some(minor) = minor {
self.minor_locator = match &minor.locator {
Some(locator) => Some(locator.clone().into_locator()?),
None => None,
};
self.minor_tick_length = minor.tick_length;
self.minor_tick_width = minor.tick_width;
self.minor_grid = minor.grid;
self.minor_grid_color = minor.grid_color;
self.minor_grid_linewidth = minor.grid_linewidth;
self.minor_grid_alpha = minor.grid_alpha;
}
Ok(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::axis::ticker::{FixedFormatter, FixedLocator, NullLocator};
/// Fixed labels are paired with fixed positions by index in the locator's
/// full output, not among the ticks that happen to be in view: clipping
/// the first position out of range must drop its label with it.
#[test]
fn visible_ticks_pairs_labels_before_range_filter() {
let mut axis = Axis::new(AxisSide::Bottom);
axis.set_locator(Box::new(FixedLocator::new(vec![-1.0, 0.0, 1.0, 2.0])));
axis.set_formatter(Box::new(FixedFormatter::from_labels(["a", "b", "c", "d"])));
let (ticks, labels) = axis.visible_ticks((0.0, 2.0));
assert_eq!(ticks, vec![0.0, 1.0, 2.0]);
assert_eq!(labels, vec!["b", "c", "d"]);
// Inverted limits clip the same way.
let (ticks, labels) = axis.visible_ticks((2.0, 0.0));
assert_eq!(ticks, vec![0.0, 1.0, 2.0]);
assert_eq!(labels, vec!["b", "c", "d"]);
}
/// A [`Renderer`] that counts `draw_path` calls and records the bbox of each
/// path's vertices (after applying the transform), for assertions.
#[derive(Default)]
struct CountingRenderer {
paths: usize,
verts: Vec<[f64; 2]>,
path_bboxes: Vec<(f64, f64, f64, f64)>,
/// The stroke width of each unfilled path, in draw order.
stroke_widths: Vec<f64>,
}
impl Renderer for CountingRenderer {
fn draw_path(
&mut self,
gc: &GraphicsContext,
path: &Path,
transform: &Affine2D,
fill: Option<Rgba>,
) {
self.paths += 1;
if fill.is_none() {
self.stroke_widths.push(gc.line_width);
}
let mut xmin = f64::INFINITY;
let mut xmax = f64::NEG_INFINITY;
let mut ymin = f64::INFINITY;
let mut ymax = f64::NEG_INFINITY;
for &[x, y] in path.vertices() {
let (tx, ty) = transform.transform_point((x, y));
self.verts.push([tx, ty]);
xmin = xmin.min(tx);
xmax = xmax.max(tx);
ymin = ymin.min(ty);
ymax = ymax.max(ty);
}
if xmin.is_finite() {
self.path_bboxes.push((xmin, xmax, ymin, ymax));
}
}
fn canvas_size(&self) -> (f64, f64) {
(300.0, 300.0)
}
}
#[test]
fn bottom_tick_positions_are_monotonic_and_span_bbox() {
let axis = Axis::new(AxisSide::Bottom);
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let xs: Vec<f64> = [0.0, 2.0, 4.0, 6.0, 8.0, 10.0]
.iter()
.map(|&v| axis.data_to_pixel(v, &bbox, 0.0, 10.0))
.collect();
// Monotonic increasing.
for w in xs.windows(2) {
assert!(w[1] > w[0], "not monotonic: {xs:?}");
}
// Spans ~[50, 250].
assert!((xs[0] - 50.0).abs() < 1e-9, "min was {}", xs[0]);
assert!((xs[xs.len() - 1] - 250.0).abs() < 1e-9, "max was {}", xs[5]);
}
#[test]
fn draw_emits_spine_ticks_and_labels() {
let axis = Axis::new(AxisSide::Bottom);
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (0.0, 10.0), &font);
// AutoLocator on [0,10] yields ticks {0,2,...,10} (6 within range).
let ticks: Vec<f64> = AutoLocator::new()
.tick_values(0.0, 10.0)
.into_iter()
.filter(|&t| (0.0..=10.0).contains(&t))
.collect();
let n = ticks.len();
assert!(n >= 5, "unexpected tick count {n}");
// spine(1) + one per tick + one per label.
assert!(
r.paths >= 1 + n + n,
"expected >= {} draw_path calls, got {}",
1 + 2 * n,
r.paths
);
}
#[test]
fn left_axis_ticks_point_left_of_spine() {
let axis = Axis::new(AxisSide::Left);
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (0.0, 10.0), &font);
// Some tick/label vertices must lie left of the spine (x < 50).
assert!(
r.verts.iter().any(|&[x, _]| x < 50.0),
"expected ink left of the left spine"
);
}
#[test]
fn tick_labels_render_mathtext_formatter_output() {
let axis = Axis::new(AxisSide::Bottom)
.with_locator(Box::new(FixedLocator::new(vec![1.0])))
.with_formatter(Box::new(FixedFormatter::new(vec!["$10^{6}$".to_string()])));
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (1.0, 1.0), &font);
// spine + tick + multiple mathtext glyph paths. The old plain-text
// route emitted only one label path containing literal '$' and braces.
assert!(
r.paths > 3,
"expected mathtext label to emit multiple paths, got {}",
r.paths
);
}
#[test]
fn axis_label_renders_mathtext() {
let axis = Axis::new(AxisSide::Left)
.with_locator(Box::new(NullLocator))
.with_label("$x^2$");
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (0.0, 1.0), &font);
// spine + multiple axis-label mathtext paths. The old plain-text route
// emitted the whole "$x^2$" label as one literal path.
assert!(
r.paths > 2,
"expected mathtext axis label to add multiple paths, got {}",
r.paths
);
}
#[test]
fn left_axis_label_is_rotated_vertically() {
let axis = Axis::new(AxisSide::Left)
.with_locator(Box::new(NullLocator))
.with_label("Voltage");
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (0.0, 1.0), &font);
let &(xmin, xmax, ymin, ymax) = r.path_bboxes.last().expect("axis label path");
let width = xmax - xmin;
let height = ymax - ymin;
assert!(
height > width * 2.0,
"expected rotated vertical label, bbox was width={width}, height={height}"
);
let center_y = (ymin + ymax) / 2.0;
assert!(
(center_y - 150.0).abs() < 20.0,
"expected ylabel centered on axes, bbox center_y={center_y}"
);
}
#[test]
fn axis_label_offset_includes_wide_tick_label_band() {
let axis = Axis::new(AxisSide::Left)
.with_locator(Box::new(FixedLocator::new(vec![1.0])))
.with_formatter(Box::new(FixedFormatter::new(vec!["1000000".to_string()])))
.with_label("value");
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (1.0, 1.0), &font);
let tick_label = r
.path_bboxes
.iter()
.rev()
.nth(1)
.expect("tick label path before axis label");
let axis_label = r.path_bboxes.last().expect("axis label path");
assert!(
axis_label.1 < tick_label.0,
"axis label should sit left of the measured tick-label band: axis={axis_label:?}, tick={tick_label:?}"
);
}
/// Minor ticks subdivide the axis' own (fixed) majors, skip positions a
/// major already holds, and every stroke keeps its sub-unit width.
#[test]
fn minor_ticks_and_grid_draw_between_fixed_majors_at_thin_widths() {
let mut axis = Axis::new(AxisSide::Bottom)
.with_locator(Box::new(FixedLocator::new(vec![0.0, 5.0, 10.0])));
axis.set_tick_labels_visible(false)
.set_tick_width(0.3)
.minorticks_on()
.set_minor_tick_params(2.0, 0.2)
.set_minor_grid(true)
.set_minor_grid_style(Rgba::BLACK, 0.25, 0.5);
assert_eq!(
axis.visible_minor_ticks((0.0, 10.0)),
vec![1.0, 2.0, 3.0, 4.0, 6.0, 7.0, 8.0, 9.0]
);
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (0.0, 10.0), &font);
// 8 minor grid lines, the spine, 3 major ticks, then 8 minor ticks.
let mut expected = vec![0.25; 8];
expected.extend([0.3; 4]);
expected.extend([0.2; 8]);
assert_eq!(r.stroke_widths, expected);
}
/// Odd-width lines centre on a pixel, even-width lines on a boundary, and
/// sub-pixel widths count as one pixel.
#[test]
fn snapping_puts_thin_lines_on_whole_pixels() {
assert_eq!(snap_to_pixel(10.0, 1.0), 10.5);
assert_eq!(snap_to_pixel(10.7, 0.36), 10.5);
assert_eq!(snap_to_pixel(10.7, 3.0), 10.5);
assert_eq!(snap_to_pixel(10.4, 2.0), 10.0);
assert_eq!(snap_to_pixel(10.6, 2.0), 11.0);
assert!(snap_to_pixel(f64::NAN, 1.0).is_nan());
}
/// Without minor ticks nothing extra is drawn, and a zero width hides the
/// spine and major ticks rather than clamping them up to one unit.
#[test]
fn minor_ticks_are_off_by_default_and_zero_width_hides_ticks() {
let mut axis = Axis::new(AxisSide::Bottom)
.with_locator(Box::new(FixedLocator::new(vec![0.0, 5.0, 10.0])));
axis.set_tick_labels_visible(false);
assert!(axis.visible_minor_ticks((0.0, 10.0)).is_empty());
let bbox = Bbox::from_extents(50.0, 50.0, 250.0, 250.0);
let font = FontSource::dejavu_sans();
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (0.0, 10.0), &font);
assert_eq!(r.stroke_widths, vec![1.0; 4]);
axis.set_tick_width(0.0);
let mut r = CountingRenderer::default();
axis.draw(&mut r, &bbox, (0.0, 10.0), &font);
assert!(r.stroke_widths.is_empty());
}
}