1use crate::coord::Coord;
2use crate::render::backend::{DrawBackend, LineStyle, TextAnchor, TextStyle};
3use crate::render::text::{axis_label_priority, label_bbox, text_width};
4use crate::render::{Rect, RenderError};
5use crate::scale::Scale;
6use crate::theme::{AxisLabelFit, Theme};
7
8fn along_x(coord: &dyn Coord, pos: f64, area: &Rect) -> f64 {
12 let p = if coord.is_flipped() {
13 (0.0, pos)
14 } else {
15 (pos, 0.0)
16 };
17 coord.transform(p, area).0
18}
19
20fn along_y(coord: &dyn Coord, pos: f64, area: &Rect) -> f64 {
22 let p = if coord.is_flipped() {
23 (pos, 0.0)
24 } else {
25 (0.0, pos)
26 };
27 coord.transform(p, area).1
28}
29
30pub fn draw_x_axis(
38 scale: &dyn Scale,
39 coord: &dyn Coord,
40 theme: &Theme,
41 plot_area: &Rect,
42 canvas: &Rect,
43 backend: &mut dyn DrawBackend,
44) -> Result<(), RenderError> {
45 draw_x_axis_with(scale, coord, theme, plot_area, canvas, true, backend)
46}
47
48pub(crate) fn draw_x_axis_with(
51 scale: &dyn Scale,
52 coord: &dyn Coord,
53 theme: &Theme,
54 plot_area: &Rect,
55 canvas: &Rect,
56 with_title: bool,
57 backend: &mut dyn DrawBackend,
58) -> Result<(), RenderError> {
59 let top = scale.axis_position_opposite();
61 let top_theme;
63 let theme = match (&theme.axis_text_x_top, top) {
64 (Some(el), true) => {
65 top_theme = Theme {
66 axis_text_x: el.clone(),
67 ..theme.clone()
68 };
69 &top_theme
70 }
71 _ => theme,
72 };
73 let breaks = scale.breaks();
74 let tick_len = theme.ticks_len_x();
75 let side = if top {
76 crate::theme::AxisSide::Top
77 } else {
78 crate::theme::AxisSide::Bottom
79 };
80 let axis_line = theme.axis_line_at(side);
81 let axis_ticks = theme.axis_ticks_at(side);
82
83 let edge_y = if top {
84 plot_area.y
85 } else {
86 plot_area.y + plot_area.height
87 };
88 let dir = if top { -1.0 } else { 1.0 };
89
90 if axis_line.visible {
92 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-line"));
93 backend.draw_line(
94 &[
95 (plot_area.x, edge_y),
96 (plot_area.x + plot_area.width, edge_y),
97 ],
98 &LineStyle {
99 color: axis_line.color,
100 width: axis_line.width,
101 alpha: 1.0,
102 linetype: axis_line.linetype.clone(),
103 ..Default::default()
104 },
105 )?;
106 }
107
108 let label_draw: Vec<Option<f64>> = if theme.axis_text_x.visible {
113 let angle = theme.axis_text_x.angle;
114 let rotated = angle.abs() > 10.0;
115 let anchor_frac = if rotated {
116 crate::render::text::rotated_anchor_frac(angle, dir)
117 } else {
118 0.5
119 };
120 let fit = theme.axis_text_x_fit;
121 let canvas_lo = canvas.x;
122 let canvas_hi = canvas.x + canvas.width;
123 const EDGE: f64 = 1.0;
124 let size = theme.axis_text_x.size;
125
126 let onscreen: Vec<(usize, f64, &str)> = breaks
130 .iter()
131 .enumerate()
132 .map(|(i, (pos, label))| (i, along_x(coord, *pos, plot_area), label.as_str()))
133 .filter(|(_, px, _)| (canvas_lo..=canvas_hi).contains(px))
134 .collect();
135
136 let mut keep = vec![true; onscreen.len()];
140 if theme.axis_text_x_check_overlap && onscreen.len() > 1 {
141 let n = onscreen.len();
142 let mut kept: Vec<(f64, f64, f64)> = Vec::with_capacity(n); keep = vec![false; n];
144 let min_gap = text_width(" ", size);
158 for p in axis_label_priority(n) {
159 let idx = p - 1; let (_, px, label) = onscreen[idx];
161 let bbox = label_bbox(label, size, px, 0.0, angle, anchor_frac);
162 let overlaps = kept.iter().any(|&(kx0, kx2, kpx)| {
163 if !rotated {
164 bbox[0] < kx2 + min_gap && bbox[2] > kx0 - min_gap
165 } else {
166 (px - kpx).abs() * angle.to_radians().sin().abs() < size
170 }
171 });
172 if !overlaps {
173 keep[idx] = true;
174 kept.push((bbox[0], bbox[2], px));
175 }
176 }
177 }
178
179 let mut draw = vec![None; breaks.len()];
180 for (k, &(i, px, label)) in onscreen.iter().enumerate() {
181 if !keep[k] {
182 continue;
183 }
184 let lx = if fit == AxisLabelFit::Clip {
187 px
188 } else {
189 let bbox = label_bbox(label, size, px, 0.0, angle, anchor_frac);
191 let room_hi = canvas_hi - EDGE;
192 let room_lo = canvas_lo + EDGE;
193 if bbox[0] < room_lo {
194 px + (room_lo - bbox[0])
195 } else if bbox[2] > room_hi {
196 px - (bbox[2] - room_hi).min(bbox[0] - room_lo)
197 } else {
198 px
199 }
200 };
201 draw[i] = Some(lx);
202 }
203 draw
204 } else {
205 Vec::new()
206 };
207
208 let dodge = theme.axis_text_x_dodge.max(1);
210 let family = if theme.axis_text_x.family.is_empty() {
211 None
212 } else {
213 Some(theme.axis_text_x.family.clone())
214 };
215 let rotated = theme.axis_text_x.angle.abs() > 10.0;
216 let draw_anchor_frac = if rotated {
221 crate::render::text::rotated_anchor_frac(theme.axis_text_x.angle, dir)
222 } else {
223 0.5
224 };
225 let anchor = if !rotated {
226 TextAnchor::Middle
227 } else if draw_anchor_frac >= 1.0 {
228 TextAnchor::End
229 } else {
230 TextAnchor::Start
231 };
232 let rotation_margin = if rotated {
242 let (rise, fall) = crate::render::text::rotated_label_rise_fall(
243 breaks
244 .iter()
245 .filter(|(_, l)| !l.is_empty())
246 .map(|(_, l)| l.as_str()),
247 theme.axis_text_x.size,
248 theme.axis_text_x.angle,
249 draw_anchor_frac,
250 );
251 if dir > 0.0 {
252 rise
253 } else {
254 fall
255 }
256 } else {
257 0.0
258 };
259 for (i, (pos, label)) in breaks.iter().enumerate() {
260 let px = along_x(coord, *pos, plot_area);
261
262 if axis_ticks.visible {
263 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-tick"));
264 backend.draw_line(
265 &[(px, edge_y), (px, edge_y + dir * tick_len)],
266 &LineStyle {
267 color: axis_ticks.color,
268 width: axis_ticks.width,
269 alpha: 1.0,
270 linetype: axis_ticks.linetype.clone(),
271 ..Default::default()
272 },
273 )?;
274 }
275
276 if let Some(Some(lx)) = label_draw.get(i) {
277 let row_offset = (i % dodge) as f64 * (theme.axis_text_x.size + 2.0);
279 let ly = edge_y
280 + dir
281 * (tick_len
282 + theme.legend_spacing / 2.0
283 + theme.axis_text_x.size / 2.0
284 + row_offset
285 + rotation_margin);
286 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-text"));
287 backend.draw_text(
288 label,
289 (*lx, ly),
290 &TextStyle {
291 color: theme.axis_text_x.color,
292 size: theme.axis_text_x.size,
293 anchor: anchor.clone(),
294 angle: theme.axis_text_x.angle,
295 family: family.clone(),
296 face: theme.axis_text_x.face,
297 bg_colour: None,
298 bg_r: 0.0,
299 },
300 )?;
301 }
302 }
303
304 if theme.axis_minor_ticks && axis_ticks.visible {
306 for pos in minor_breaks(&breaks) {
307 let px = along_x(coord, pos, plot_area);
308 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-tick"));
309 backend.draw_line(
310 &[(px, edge_y), (px, edge_y + dir * tick_len * 0.5)],
311 &LineStyle {
312 color: axis_ticks.color,
313 width: axis_ticks.width,
314 alpha: 1.0,
315 linetype: axis_ticks.linetype.clone(),
316 ..Default::default()
317 },
318 )?;
319 }
320 }
321
322 if axis_ticks.visible {
324 for (pos, kind) in scale.log_ticks() {
325 let px = along_x(coord, pos, plot_area);
326 let len = tick_len * [2.25, 1.5, 0.75][kind as usize];
327 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-tick"));
328 backend.draw_line(
329 &[(px, edge_y), (px, edge_y + dir * len)],
330 &LineStyle {
331 color: axis_ticks.color,
332 width: axis_ticks.width,
333 alpha: 1.0,
334 linetype: axis_ticks.linetype.clone(),
335 ..Default::default()
336 },
337 )?;
338 }
339 }
340
341 if with_title {
342 draw_x_axis_title(scale, theme, plot_area, backend)?;
343 }
344
345 Ok(())
346}
347
348pub(crate) fn draw_x_axis_title(
351 scale: &dyn Scale,
352 theme: &Theme,
353 area: &Rect,
354 backend: &mut dyn DrawBackend,
355) -> Result<(), RenderError> {
356 let plot_area = area;
357 let tick_len = theme.ticks_len_x();
358 let top = scale.axis_position_opposite();
359 let edge_y = if top {
360 plot_area.y
361 } else {
362 plot_area.y + plot_area.height
363 };
364 let dir = if top { -1.0 } else { 1.0 };
365 let title = scale.name();
366 if !title.is_empty() && theme.axis_title_x.visible {
367 let hjust = theme.axis_title_x.hjust.clamp(0.0, 1.0);
368 let center_x = plot_area.x + hjust * plot_area.width;
369 let anchor = if hjust <= 0.02 {
370 TextAnchor::Start
371 } else if hjust >= 0.98 {
372 TextAnchor::End
373 } else {
374 TextAnchor::Middle
375 };
376 let angle = theme.axis_text_x.angle;
380 let labels_h = if theme.axis_text_x.visible && angle.abs() > 10.0 {
381 let breaks = scale.breaks();
382 let (rise, fall) = crate::render::text::rotated_label_rise_fall(
383 breaks.iter().map(|(_, l)| l.as_str()),
384 theme.axis_text_x.size,
385 angle,
386 crate::render::text::rotated_anchor_frac(angle, dir),
387 );
388 (rise + fall).max(theme.axis_text_x.size)
389 } else {
390 theme.axis_text_x.size
391 };
392 let title_y = edge_y + dir * (tick_len + labels_h + 8.0 + theme.axis_title_x.size / 2.0);
393 let family = if theme.axis_title_x.family.is_empty() {
394 None
395 } else {
396 Some(theme.axis_title_x.family.clone())
397 };
398 backend.set_element_class(Some("gg-axis-title gg-axis-title-x"));
399 crate::render::rich::draw(
400 backend,
401 theme.rich_text,
402 title,
403 (center_x, title_y),
404 &TextStyle {
405 color: theme.axis_title_x.color,
406 size: theme.axis_title_x.size,
407 anchor,
408 angle: 0.0,
409 family,
410 face: theme.axis_title_x.face,
411 bg_colour: None,
412 bg_r: 0.0,
413 },
414 )?;
415 }
416
417 Ok(())
418}
419
420pub fn draw_y_axis(
422 scale: &dyn Scale,
423 coord: &dyn Coord,
424 theme: &Theme,
425 plot_area: &Rect,
426 backend: &mut dyn DrawBackend,
427) -> Result<(), RenderError> {
428 draw_y_axis_with(scale, coord, theme, plot_area, true, backend)
429}
430
431pub(crate) fn draw_y_axis_with(
434 scale: &dyn Scale,
435 coord: &dyn Coord,
436 theme: &Theme,
437 plot_area: &Rect,
438 with_title: bool,
439 backend: &mut dyn DrawBackend,
440) -> Result<(), RenderError> {
441 let breaks = scale.breaks();
442 let tick_len = theme.ticks_len_y();
443 let axis_line = theme.axis_line_at(crate::theme::AxisSide::Left);
444 let axis_ticks = theme.axis_ticks_at(crate::theme::AxisSide::Left);
445
446 if axis_line.visible {
448 let top = (plot_area.x, plot_area.y);
449 let bottom = (plot_area.x, plot_area.y + plot_area.height);
450 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-line"));
451 backend.draw_line(
452 &[top, bottom],
453 &LineStyle {
454 color: axis_line.color,
455 width: axis_line.width,
456 alpha: 1.0,
457 linetype: axis_line.linetype.clone(),
458 ..Default::default()
459 },
460 )?;
461 }
462
463 let title_band = if with_title && !scale.name().is_empty() && theme.axis_title_y.visible {
469 theme.axis_title_y.size + Y_TITLE_GAP
470 } else {
471 0.0
472 };
473 let label_room =
474 plot_area.x - tick_len - theme.legend_spacing - backend.total_area().x - title_band - 2.0;
475
476 for (pos, label) in &breaks {
478 let py = along_y(coord, *pos, plot_area);
479
480 if axis_ticks.visible {
481 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-tick"));
482 backend.draw_line(
483 &[(plot_area.x - tick_len, py), (plot_area.x, py)],
484 &LineStyle {
485 color: axis_ticks.color,
486 width: axis_ticks.width,
487 alpha: 1.0,
488 linetype: axis_ticks.linetype.clone(),
489 ..Default::default()
490 },
491 )?;
492 }
493
494 if theme.axis_text_y.visible {
495 let family = if theme.axis_text_y.family.is_empty() {
496 None
497 } else {
498 Some(theme.axis_text_y.family.clone())
499 };
500 let label = if theme.axis_text_y.angle == 0.0 {
501 fit_label(label, theme.axis_text_y.size, label_room)
502 } else {
503 std::borrow::Cow::Borrowed(label.as_str())
504 };
505 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-text"));
506 backend.draw_text(
507 &label,
508 (plot_area.x - tick_len - theme.legend_spacing, py),
509 &TextStyle {
510 color: theme.axis_text_y.color,
511 size: theme.axis_text_y.size,
512 anchor: TextAnchor::End,
513 angle: theme.axis_text_y.angle,
514 family,
515 face: theme.axis_text_y.face,
516 bg_colour: None,
517 bg_r: 0.0,
518 },
519 )?;
520 }
521 }
522
523 if theme.axis_minor_ticks && axis_ticks.visible {
525 for pos in minor_breaks(&breaks) {
526 let py = along_y(coord, pos, plot_area);
527 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-tick"));
528 backend.draw_line(
529 &[(plot_area.x - tick_len * 0.5, py), (plot_area.x, py)],
530 &LineStyle {
531 color: axis_ticks.color,
532 width: axis_ticks.width,
533 alpha: 1.0,
534 linetype: axis_ticks.linetype.clone(),
535 ..Default::default()
536 },
537 )?;
538 }
539 }
540
541 if axis_ticks.visible {
543 for (pos, kind) in scale.log_ticks() {
544 let py = along_y(coord, pos, plot_area);
545 let len = tick_len * [2.25, 1.5, 0.75][kind as usize];
546 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-tick"));
547 backend.draw_line(
548 &[(plot_area.x - len, py), (plot_area.x, py)],
549 &LineStyle {
550 color: axis_ticks.color,
551 width: axis_ticks.width,
552 alpha: 1.0,
553 linetype: axis_ticks.linetype.clone(),
554 ..Default::default()
555 },
556 )?;
557 }
558 }
559
560 if with_title {
561 let reserve = y_label_reserve(theme, &breaks);
562 draw_y_axis_title(scale, theme, plot_area, reserve, backend)?;
563 }
564
565 Ok(())
566}
567
568fn fit_label(label: &str, size: f64, room: f64) -> std::borrow::Cow<'_, str> {
573 let text_width = |t: &str, size: f64| crate::render::text::text_width(t, size) * 1.08;
574 if room < size || text_width(label, size) <= room {
575 return std::borrow::Cow::Borrowed(label);
576 }
577 let chars: Vec<char> = label.chars().collect();
578 for n in (1..chars.len()).rev() {
579 let cand: String =
580 chars[..n].iter().collect::<String>().trim_end().to_string() + "\u{2026}";
581 if text_width(&cand, size) <= room {
582 return std::borrow::Cow::Owned(cand);
583 }
584 }
585 std::borrow::Cow::Owned("\u{2026}".into())
586}
587
588const Y_TITLE_GAP: f64 = 4.0;
590
591pub(crate) fn y_label_reserve(theme: &Theme, breaks: &[(f64, String)]) -> f64 {
594 let max_ch = breaks
595 .iter()
596 .map(|(_, l)| l.chars().count())
597 .max()
598 .unwrap_or(0);
599 let measured = max_ch as f64 * theme.axis_text_y.size * 0.6 + 4.0;
600 let default = theme.axis_text_y.size * 3.5 + 4.0;
601 measured.max(default)
602}
603
604pub(crate) fn draw_y_axis_title(
607 scale: &dyn Scale,
608 theme: &Theme,
609 area: &Rect,
610 label_reserve: f64,
611 backend: &mut dyn DrawBackend,
612) -> Result<(), RenderError> {
613 let title = scale.name();
614 if !title.is_empty() && theme.axis_title_y.visible {
615 let size = theme.axis_title_y.size;
620 let right = area.x - theme.ticks_len_y() - label_reserve - Y_TITLE_GAP;
621 let min_x = backend.total_area().x + 0.75 * size;
622 let title_x = (right - 0.25 * size).max(min_x);
623 let center_y = area.y + area.height / 2.0;
624 let family = if theme.axis_title_y.family.is_empty() {
625 None
626 } else {
627 Some(theme.axis_title_y.family.clone())
628 };
629 backend.set_element_class(Some("gg-axis-title gg-axis-title-y"));
630 crate::render::rich::draw(
631 backend,
632 theme.rich_text,
633 title,
634 (title_x, center_y),
635 &TextStyle {
636 color: theme.axis_title_y.color,
637 size: theme.axis_title_y.size,
638 anchor: TextAnchor::Middle,
639 angle: 270.0,
640 family,
641 face: theme.axis_title_y.face,
642 bg_colour: None,
643 bg_r: 0.0,
644 },
645 )?;
646 }
647
648 Ok(())
649}
650
651pub fn draw_sec_y_axis(
653 primary_scale: &dyn Scale,
654 sec_axis: &crate::scale::sec_axis::SecAxis,
655 coord: &dyn Coord,
656 theme: &Theme,
657 plot_area: &Rect,
658 backend: &mut dyn DrawBackend,
659) -> Result<(), RenderError> {
660 let right_theme;
662 let theme = match &theme.axis_text_y_right {
663 Some(el) => {
664 right_theme = Theme {
665 axis_text_y: el.clone(),
666 ..theme.clone()
667 };
668 &right_theme
669 }
670 None => theme,
671 };
672 let own_ticks = sec_axis.own_ticks(primary_scale);
673 let breaks = own_ticks.clone().unwrap_or_else(|| primary_scale.breaks());
674 let tick_len = theme.ticks_len_y();
675 let axis_line = theme.axis_line_at(crate::theme::AxisSide::Right);
676 let axis_ticks = theme.axis_ticks_at(crate::theme::AxisSide::Right);
677
678 let right_x = plot_area.x + plot_area.width;
679
680 if axis_line.visible {
682 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-line"));
683 backend.draw_line(
684 &[
685 (right_x, plot_area.y),
686 (right_x, plot_area.y + plot_area.height),
687 ],
688 &LineStyle {
689 color: axis_line.color,
690 width: axis_line.width,
691 alpha: 1.0,
692 linetype: axis_line.linetype.clone(),
693 ..Default::default()
694 },
695 )?;
696 }
697
698 for (pos, label) in &breaks {
700 let py = along_y(coord, *pos, plot_area);
701
702 if axis_ticks.visible {
703 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-tick"));
704 backend.draw_line(
705 &[(right_x, py), (right_x + tick_len, py)],
706 &LineStyle {
707 color: axis_ticks.color,
708 width: axis_ticks.width,
709 alpha: 1.0,
710 linetype: axis_ticks.linetype.clone(),
711 ..Default::default()
712 },
713 )?;
714 }
715
716 if theme.axis_text_y.visible {
717 let locale = primary_scale.locale();
719 let parsed = match locale {
720 Some(l) => l.parse_number(label),
721 None => label.parse::<f64>().ok(),
722 };
723 let sec_label = if own_ticks.is_some() {
724 label.clone()
725 } else if let Some(v) = parsed {
726 sec_axis.label(sec_axis.transform_value(v), locale)
727 } else {
728 label.clone()
729 };
730
731 let family = if theme.axis_text_y.family.is_empty() {
732 None
733 } else {
734 Some(theme.axis_text_y.family.clone())
735 };
736 backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-text"));
737 backend.draw_text(
738 &sec_label,
739 (right_x + tick_len + theme.legend_spacing, py),
740 &TextStyle {
741 color: theme.axis_text_y.color,
742 size: theme.axis_text_y.size,
743 anchor: TextAnchor::Start,
744 angle: theme.axis_text_y.angle,
745 family,
746 face: theme.axis_text_y.face,
747 bg_colour: None,
748 bg_r: 0.0,
749 },
750 )?;
751 }
752 }
753
754 if !sec_axis.name.is_empty() && theme.axis_title_y.visible {
756 let max_ch = own_ticks
759 .as_ref()
760 .and_then(|t| t.iter().map(|(_, l)| l.chars().count()).max())
761 .unwrap_or(0);
762 let text_w =
763 (max_ch as f64 * theme.axis_text_y.size * 0.6).max(theme.axis_text_y.size * 3.5);
764 let title_x = right_x + tick_len + text_w + theme.legend_spacing;
765 let center_y = plot_area.y + plot_area.height / 2.0;
766 let family = if theme.axis_title_y.family.is_empty() {
767 None
768 } else {
769 Some(theme.axis_title_y.family.clone())
770 };
771 backend.set_element_class(Some("gg-axis-title gg-axis-title-y"));
772 crate::render::rich::draw(
773 backend,
774 theme.rich_text,
775 &sec_axis.name,
776 (title_x, center_y),
777 &TextStyle {
778 color: theme.axis_title_y.color,
779 size: theme.axis_title_y.size,
780 anchor: TextAnchor::Middle,
781 angle: 90.0,
782 family,
783 face: theme.axis_title_y.face,
784 bg_colour: None,
785 bg_r: 0.0,
786 },
787 )?;
788 }
789
790 Ok(())
791}
792
793fn sec_labels(
796 primary_scale: &dyn Scale,
797 sec_axis: &crate::scale::sec_axis::SecAxis,
798 breaks: &[(f64, String)],
799 own: bool,
800) -> Vec<String> {
801 let locale = primary_scale.locale();
802 breaks
803 .iter()
804 .map(|(_, label)| {
805 if own {
806 return label.clone();
807 }
808 let parsed = match locale {
809 Some(l) => l.parse_number(label),
810 None => label.parse::<f64>().ok(),
811 };
812 match parsed {
813 Some(v) => sec_axis.label(sec_axis.transform_value(v), locale),
814 None => label.clone(),
815 }
816 })
817 .collect()
818}
819
820pub(crate) fn sec_x_axis_height(theme: &Theme, sec_axis: &crate::scale::sec_axis::SecAxis) -> f64 {
824 theme.ticks_len_x()
825 + if theme.axis_text_x.visible {
826 theme.axis_text_x.size + 4.0
827 } else {
828 0.0
829 }
830 + if !sec_axis.name.is_empty() && theme.axis_title_x.visible {
831 theme.axis_title_x.size + 6.0
832 } else {
833 0.0
834 }
835}
836
837pub fn draw_sec_x_axis(
840 primary_scale: &dyn Scale,
841 sec_axis: &crate::scale::sec_axis::SecAxis,
842 coord: &dyn Coord,
843 theme: &Theme,
844 plot_area: &Rect,
845 backend: &mut dyn DrawBackend,
846) -> Result<(), RenderError> {
847 let own_ticks = sec_axis.own_ticks(primary_scale);
848 let breaks = own_ticks.clone().unwrap_or_else(|| primary_scale.breaks());
849 let labels = sec_labels(primary_scale, sec_axis, &breaks, own_ticks.is_some());
850 let tick_len = theme.ticks_len_x();
851 let axis_line = theme.axis_line_at(crate::theme::AxisSide::Top);
852 let axis_ticks = theme.axis_ticks_at(crate::theme::AxisSide::Top);
853 let top_y = plot_area.y;
854 let line = |el: &crate::theme::elements::ElementLine| LineStyle {
855 color: el.color,
856 width: el.width,
857 alpha: 1.0,
858 linetype: el.linetype.clone(),
859 ..Default::default()
860 };
861 if axis_line.visible {
862 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-line"));
863 backend.draw_line(
864 &[(plot_area.x, top_y), (plot_area.x + plot_area.width, top_y)],
865 &line(axis_line),
866 )?;
867 }
868 let family = |f: &str| (!f.is_empty()).then(|| f.to_string());
869 for ((pos, _), label) in breaks.iter().zip(&labels) {
870 let px = along_x(coord, *pos, plot_area);
871 if axis_ticks.visible {
872 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-tick"));
873 backend.draw_line(&[(px, top_y), (px, top_y - tick_len)], &line(axis_ticks))?;
874 }
875 if theme.axis_text_x.visible {
876 backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-text"));
877 backend.draw_text(
878 label,
879 (px, top_y - tick_len - 2.0 - theme.axis_text_x.size / 2.0),
880 &TextStyle {
881 color: theme.axis_text_x.color,
882 size: theme.axis_text_x.size,
883 anchor: TextAnchor::Middle,
884 angle: 0.0,
885 family: family(&theme.axis_text_x.family),
886 face: theme.axis_text_x.face,
887 bg_colour: None,
888 bg_r: 0.0,
889 },
890 )?;
891 }
892 }
893 if !sec_axis.name.is_empty() && theme.axis_title_x.visible {
894 let y = top_y - sec_x_axis_height(theme, sec_axis) + theme.axis_title_x.size / 2.0;
895 backend.set_element_class(Some("gg-axis-title gg-axis-title-x"));
896 crate::render::rich::draw(
897 backend,
898 theme.rich_text,
899 &sec_axis.name,
900 (plot_area.x + plot_area.width / 2.0, y),
901 &TextStyle {
902 color: theme.axis_title_x.color,
903 size: theme.axis_title_x.size,
904 anchor: TextAnchor::Middle,
905 angle: 0.0,
906 family: family(&theme.axis_title_x.family),
907 face: theme.axis_title_x.face,
908 bg_colour: None,
909 bg_r: 0.0,
910 },
911 )?;
912 }
913 Ok(())
914}
915
916fn minor_breaks(major: &[(f64, String)]) -> Vec<f64> {
918 if major.len() < 2 {
919 return vec![];
920 }
921 let mut minors = Vec::with_capacity(major.len() - 1);
922 for pair in major.windows(2) {
923 minors.push((pair[0].0 + pair[1].0) / 2.0);
924 }
925 minors
926}
927
928pub fn draw_gridlines(
930 x_scale: &dyn Scale,
931 y_scale: &dyn Scale,
932 coord: &dyn Coord,
933 theme: &Theme,
934 plot_area: &Rect,
935 backend: &mut dyn DrawBackend,
936) -> Result<(), RenderError> {
937 let major_x = theme.get_panel_grid_major_x();
938 let major_y = theme.get_panel_grid_major_y();
939 let minor_x = theme.get_panel_grid_minor_x();
940 let minor_y = theme.get_panel_grid_minor_y();
941
942 let x_breaks = x_scale.breaks();
943 let y_breaks = y_scale.breaks();
944
945 if minor_x.visible {
947 for pos in minor_breaks(&x_breaks) {
948 let px = along_x(coord, pos, plot_area);
949 backend.set_element_class(Some("gg-grid gg-grid-minor gg-grid-x"));
950 backend.draw_line(
951 &[(px, plot_area.y), (px, plot_area.y + plot_area.height)],
952 &LineStyle {
953 color: minor_x.color,
954 width: minor_x.width,
955 alpha: 1.0,
956 linetype: minor_x.linetype.clone(),
957 ..Default::default()
958 },
959 )?;
960 }
961 }
962
963 if minor_y.visible {
965 for pos in minor_breaks(&y_breaks) {
966 let py = along_y(coord, pos, plot_area);
967 backend.set_element_class(Some("gg-grid gg-grid-minor gg-grid-y"));
968 backend.draw_line(
969 &[(plot_area.x, py), (plot_area.x + plot_area.width, py)],
970 &LineStyle {
971 color: minor_y.color,
972 width: minor_y.width,
973 alpha: 1.0,
974 linetype: minor_y.linetype.clone(),
975 ..Default::default()
976 },
977 )?;
978 }
979 }
980
981 if major_x.visible {
983 for (pos, _) in &x_breaks {
984 let px = along_x(coord, *pos, plot_area);
985 backend.set_element_class(Some("gg-grid gg-grid-major gg-grid-x"));
986 backend.draw_line(
987 &[(px, plot_area.y), (px, plot_area.y + plot_area.height)],
988 &LineStyle {
989 color: major_x.color,
990 width: major_x.width,
991 alpha: 1.0,
992 linetype: major_x.linetype.clone(),
993 ..Default::default()
994 },
995 )?;
996 }
997 }
998
999 if major_y.visible {
1001 for (pos, _) in &y_breaks {
1002 let py = along_y(coord, *pos, plot_area);
1003 backend.set_element_class(Some("gg-grid gg-grid-major gg-grid-y"));
1004 backend.draw_line(
1005 &[(plot_area.x, py), (plot_area.x + plot_area.width, py)],
1006 &LineStyle {
1007 color: major_y.color,
1008 width: major_y.width,
1009 alpha: 1.0,
1010 linetype: major_y.linetype.clone(),
1011 ..Default::default()
1012 },
1013 )?;
1014 }
1015 }
1016
1017 Ok(())
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022 use super::*;
1023 use crate::aes::Aesthetic;
1024 use crate::coord::cartesian::CoordCartesian;
1025 use crate::data::Value;
1026 use crate::render::svg_backend::SvgBackend;
1027 use crate::theme::presets::theme_gray;
1028
1029 struct FixedBreaksScale(Vec<(f64, String)>);
1032
1033 impl Scale for FixedBreaksScale {
1034 fn aesthetic(&self) -> Aesthetic {
1035 Aesthetic::X
1036 }
1037 fn train(&mut self, _values: &[Value]) {}
1038 fn map(&self, _value: &Value) -> f64 {
1039 0.0
1040 }
1041 fn breaks(&self) -> Vec<(f64, String)> {
1042 self.0.clone()
1043 }
1044 fn name(&self) -> &str {
1045 ""
1046 }
1047 fn set_name(&mut self, _name: &str) {}
1048 fn clone_box(&self) -> Box<dyn Scale> {
1049 Box::new(FixedBreaksScale(self.0.clone()))
1050 }
1051 }
1052
1053 fn backend(w: u32, h: u32, plot_area: Rect) -> SvgBackend {
1054 SvgBackend::new(w, h, plot_area)
1055 }
1056
1057 #[test]
1058 fn a_tick_outside_the_svg_is_dropped() {
1059 let scale = FixedBreaksScale(vec![
1062 (0.2, "kept".to_string()),
1063 (5.0, "off_canvas".to_string()),
1064 ]);
1065 let coord = CoordCartesian::new();
1066 let theme = theme_gray();
1067 let plot_area = Rect {
1068 x: 10.0,
1069 y: 10.0,
1070 width: 180.0,
1071 height: 70.0,
1072 };
1073 let canvas = Rect {
1074 x: 0.0,
1075 y: 0.0,
1076 width: 200.0,
1077 height: 100.0,
1078 };
1079 let mut backend = backend(200, 100, plot_area.clone());
1080 draw_x_axis(&scale, &coord, &theme, &plot_area, &canvas, &mut backend).unwrap();
1081 let svg = backend.finish();
1082 assert!(svg.contains(">kept<"), "on-canvas label dropped: {svg}");
1083 assert!(
1084 !svg.contains(">off_canvas<"),
1085 "off-canvas label was drawn: {svg}"
1086 );
1087 }
1088
1089 #[test]
1090 fn clip_draws_the_label_exactly_at_the_tick_even_past_the_edge() {
1091 let scale = FixedBreaksScale(vec![
1093 (0.0, "a".to_string()),
1094 (1.0, "2021-01-01".to_string()),
1095 ]);
1096 let coord = CoordCartesian::new();
1097 let mut theme = theme_gray();
1098 theme.axis_text_x_fit = crate::theme::AxisLabelFit::Clip;
1099 let plot_area = Rect {
1100 x: 0.0,
1101 y: 0.0,
1102 width: 60.0,
1103 height: 50.0,
1104 };
1105 let canvas = plot_area.clone();
1106 let mut backend = backend(60, 50, plot_area.clone());
1107 draw_x_axis(&scale, &coord, &theme, &plot_area, &canvas, &mut backend).unwrap();
1108 let svg = backend.finish();
1109 assert!(
1112 svg.contains("x=\"60.00\" y=\"") && svg.contains(">2021-01-01<"),
1113 "clip mode should not shift the label: {svg}"
1114 );
1115 }
1116
1117 #[test]
1118 fn shift_moves_the_same_label_inside_the_canvas() {
1119 let scale = FixedBreaksScale(vec![
1120 (0.0, "a".to_string()),
1121 (1.0, "2021-01-01".to_string()),
1122 ]);
1123 let coord = CoordCartesian::new();
1124 let mut theme = theme_gray();
1125 theme.axis_text_x_fit = crate::theme::AxisLabelFit::Shift;
1126 let plot_area = Rect {
1127 x: 0.0,
1128 y: 0.0,
1129 width: 60.0,
1130 height: 50.0,
1131 };
1132 let canvas = plot_area.clone();
1133 let mut backend = backend(60, 50, plot_area.clone());
1134 draw_x_axis(&scale, &coord, &theme, &plot_area, &canvas, &mut backend).unwrap();
1135 let svg = backend.finish();
1136 assert!(
1137 !svg.contains("x=\"60.00\" y=\""),
1138 "shift mode should move the label off the bare tick: {svg}"
1139 );
1140 let w = crate::render::text::text_width("2021-01-01", theme.axis_text_x.size);
1141 let needle = ">2021-01-01<";
1143 let tag_end = svg.find(needle).unwrap();
1144 let tag_start = svg[..tag_end].rfind("<text ").unwrap();
1145 let tag = &svg[tag_start..tag_end];
1146 let x_attr = tag.rsplit("x=\"").next().unwrap();
1147 let x: f64 = x_attr.split('"').next().unwrap().parse().unwrap();
1148 assert!(
1151 x + w / 2.0 <= 60.0 - 1.0 + 0.01,
1152 "right edge still overflows: x={x} w={w}"
1153 );
1154 }
1155}
1156
1157#[cfg(test)]
1158mod fit_label_538_tests {
1159 use super::fit_label;
1160
1161 #[test]
1162 fn a_label_is_kept_shortened_or_reduced_to_an_ellipsis() {
1163 assert_eq!(fit_label("ES_bu", 11.0, 200.0), "ES_bu");
1165 assert_eq!(fit_label("a long label", 11.0, 5.0), "a long label");
1166 let cut = fit_label("one global model (anofox_ml)", 11.0, 60.0);
1168 assert!(
1169 cut.ends_with('…') && cut.len() < "one global model (anofox_ml)".len(),
1170 "{cut}"
1171 );
1172 assert!(!cut.contains(" …"), "{cut}");
1173 assert_eq!(fit_label("WWWWWWWW", 11.0, 11.5), "…");
1175 }
1176}