Skip to main content

ggplot_rs/guide/
axis.rs

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
8/// Horizontal pixel for a break at normalized `pos` along the *horizontal* axis.
9/// `coord_flip` swaps which normalized component drives horizontal position, so
10/// route through the coord with the component that lands on x either way.
11fn 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
20/// Vertical pixel for a break at normalized `pos` along the *vertical* axis.
21fn 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
30/// Draw the X axis: ticks, labels, and title.
31///
32/// `canvas` is the full SVG viewport (not just the panel): B3-1's outer-
33/// label fit drops a label whose tick has scrolled off it, and shifts a
34/// label bbox that crosses it back inside, unless
35/// `theme.axis_text_x_fit` is [`AxisLabelFit::Clip`] (the 0.21 behaviour —
36/// no correction). Ticks and gridlines are drawn regardless.
37pub 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
48/// [`draw_x_axis`], optionally without its title — a faceted grid draws one
49/// title for all panels instead (#348).
50pub(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    // Axis position: bottom (default) or top. `dir` points away from the panel.
60    let top = scale.axis_position_opposite();
61    // A top axis's labels follow `axis_text_x_top` when set (#413).
62    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    // Axis line
91    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    // Precompute, per break, whether/where its label is drawn — but keep a
109    // single loop below in the *original* per-break (tick, label) order, so
110    // a plot whose labels all fit and don't overlap renders byte-identical
111    // SVG to 0.21 (same element order), even though the decision logic ran.
112    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        // (index, px, label) for breaks whose tick is on-canvas. A label
127        // whose tick has scrolled off the canvas names nothing that is
128        // shown — unconditional, even under `Clip`.
129        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        // ggplot2's `check.overlap`: draw in priority order (first, last,
137        // then recursive midpoint bisection — D5), skipping any label that
138        // would overlap one already kept.
139        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); // (x0, x2, px)
143            keep = vec![false; n];
144            // A minimum legible gap between two *kept* labels, not just "the
145            // bboxes don't literally touch" (sipemu/ggplot-rs#212): a label-
146            // width estimate close enough to a font's real metrics (`size`'s
147            // own table is tuned for one house font) can leave adjacent
148            // labels a pixel or two apart on paper but visually touching
149            // once actually rendered — a run like "25" next to "50" then
150            // reads as the single garbled "2550". ggplot2's own
151            // check.overlap has no such margin (a print figure can afford a
152            // tight fit); this is for an interactive dashboard, where a
153            // readable gap matters more than keeping one extra label. One
154            // space character's width is a natural, already-tabulated unit
155            // for "a visually clear gap" — not print-figure kerning, just
156            // enough that two numbers never read as one.
157            let min_gap = text_width(" ", size);
158            for p in axis_label_priority(n) {
159                let idx = p - 1; // 1-indexed in the ggplot2 sense
160                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                        // Parallel rotated labels on one baseline: the
167                        // perpendicular distance across the text direction
168                        // must leave room for a line of text.
169                        (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            // Shift a bbox that crosses the canvas edge back inside (moving
185            // the rotate centre too), unless `fit` is `Clip` (0.21 behaviour).
186            let lx = if fit == AxisLabelFit::Clip {
187                px
188            } else {
189                // `ly` doesn't affect the x-bbox; 0.0 is a placeholder.
190                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    // Ticks and labels, interleaved in break order (ticks always stay).
209    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    // Which end of the text pins to the tick, so the near-axis end stays
217    // there instead of the whole label sliding away (sipemu/ggplot-rs#163)
218    // — depends on both the rotation's direction and which side of the
219    // axis line the panel is on (`dir`); see `rotated_anchor_frac`.
220    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    // A rotated label's far end swings back *toward* the panel on one side
233    // and away from it on the other (sipemu/ggplot-rs#162) — toward the
234    // panel is `rise` for a bottom axis (`dir > 0`, the panel sits above
235    // the axis line) and `fall` for a top axis (`dir < 0`, the panel sits
236    // below it). Reserving only `rotated_label_rise_fall`'s sum (as
237    // `layout_built` does, for the *other* side's on-canvas extent) isn't
238    // enough on its own: this offset must actually place the rotation
239    // anchor that far from the axis line, or a long enough label swings
240    // right back over the panel no matter how much height was reserved.
241    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            // Stagger labels across `dodge` rows to avoid overlap.
278            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    // Minor ticks between majors.
305    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    // `guide_axis_logticks()` (#409): ggplot2's 2.25 / 1.5 / 0.75 lengths.
323    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
348/// The x axis title, placed against `area`'s bottom (or top, for an
349/// opposite axis) edge and spanning its width.
350pub(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        // #482: below rotated labels (auto-rotated to -45°/270°, or an
377        // explicit angle) the title clears their real extent — the same
378        // rise/fall the layout reserves for them — not one line of text.
379        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
420/// Draw the Y axis: ticks, labels, and title.
421pub 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
431/// [`draw_y_axis`], optionally without its title — a faceted grid draws one
432/// title for all panels instead (#348).
433pub(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    // Axis line
447    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    // #538: the room left of the panel for a tick label — to the canvas
464    // edge, less the y title's band when one is drawn. The layout reserves
465    // up to 35 % of the width for long labels; a label still wider than the
466    // room left (a narrow plot) is shortened with "…" instead of running
467    // off the canvas. Labels that fit are drawn exactly as before.
468    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    // Ticks and labels
477    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    // Minor ticks between majors.
524    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    // `guide_axis_logticks()` (#409).
542    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
568/// `label` shortened with "…" to `room` px at `size` (#538); as it was when
569/// it fits, or when there is no room to speak of.
570fn fit_label(label: &str, size: f64, room: f64) -> std::borrow::Cow<'_, str> {
571    use crate::render::text::text_width;
572    if room < size || text_width(label, size) <= room {
573        return std::borrow::Cow::Borrowed(label);
574    }
575    let chars: Vec<char> = label.chars().collect();
576    for n in (1..chars.len()).rev() {
577        let cand: String =
578            chars[..n].iter().collect::<String>().trim_end().to_string() + "\u{2026}";
579        if text_width(&cand, size) <= room {
580            return std::borrow::Cow::Owned(cand);
581        }
582    }
583    std::borrow::Cow::Owned("\u{2026}".into())
584}
585
586/// Gap between the y tick labels and the y axis title (#348).
587const Y_TITLE_GAP: f64 = 4.0;
588
589/// Width the layout reserves for the y tick labels with these `breaks`
590/// (estimated from their length; never below the theme default).
591pub(crate) fn y_label_reserve(theme: &Theme, breaks: &[(f64, String)]) -> f64 {
592    let max_ch = breaks
593        .iter()
594        .map(|(_, l)| l.chars().count())
595        .max()
596        .unwrap_or(0);
597    let measured = max_ch as f64 * theme.axis_text_y.size * 0.6 + 4.0;
598    let default = theme.axis_text_y.size * 3.5 + 4.0;
599    measured.max(default)
600}
601
602/// The y axis title, left of `area`'s tick labels (`label_reserve` wide)
603/// and centred on its height.
604pub(crate) fn draw_y_axis_title(
605    scale: &dyn Scale,
606    theme: &Theme,
607    area: &Rect,
608    label_reserve: f64,
609    backend: &mut dyn DrawBackend,
610) -> Result<(), RenderError> {
611    let title = scale.name();
612    if !title.is_empty() && theme.axis_title_y.visible {
613        // The rotated (270°) title's glyphs span roughly [x − 0.75·size,
614        // x + 0.25·size]; keep its right edge a fixed gap (ggplot2's
615        // 2.75pt title margin) left of the tick-label column the layout
616        // reserved — never overlapping short labels — and on the canvas.
617        let size = theme.axis_title_y.size;
618        let right = area.x - theme.ticks_len_y() - label_reserve - Y_TITLE_GAP;
619        let min_x = backend.total_area().x + 0.75 * size;
620        let title_x = (right - 0.25 * size).max(min_x);
621        let center_y = area.y + area.height / 2.0;
622        let family = if theme.axis_title_y.family.is_empty() {
623            None
624        } else {
625            Some(theme.axis_title_y.family.clone())
626        };
627        backend.set_element_class(Some("gg-axis-title gg-axis-title-y"));
628        crate::render::rich::draw(
629            backend,
630            theme.rich_text,
631            title,
632            (title_x, center_y),
633            &TextStyle {
634                color: theme.axis_title_y.color,
635                size: theme.axis_title_y.size,
636                anchor: TextAnchor::Middle,
637                angle: 270.0,
638                family,
639                face: theme.axis_title_y.face,
640                bg_colour: None,
641                bg_r: 0.0,
642            },
643        )?;
644    }
645
646    Ok(())
647}
648
649/// Draw a secondary Y axis on the right side.
650pub fn draw_sec_y_axis(
651    primary_scale: &dyn Scale,
652    sec_axis: &crate::scale::sec_axis::SecAxis,
653    coord: &dyn Coord,
654    theme: &Theme,
655    plot_area: &Rect,
656    backend: &mut dyn DrawBackend,
657) -> Result<(), RenderError> {
658    // The right axis's labels follow `axis_text_y_right` when set (#413).
659    let right_theme;
660    let theme = match &theme.axis_text_y_right {
661        Some(el) => {
662            right_theme = Theme {
663                axis_text_y: el.clone(),
664                ..theme.clone()
665            };
666            &right_theme
667        }
668        None => theme,
669    };
670    let own_ticks = sec_axis.own_ticks(primary_scale);
671    let breaks = own_ticks.clone().unwrap_or_else(|| primary_scale.breaks());
672    let tick_len = theme.ticks_len_y();
673    let axis_line = theme.axis_line_at(crate::theme::AxisSide::Right);
674    let axis_ticks = theme.axis_ticks_at(crate::theme::AxisSide::Right);
675
676    let right_x = plot_area.x + plot_area.width;
677
678    // Axis line on right side
679    if axis_line.visible {
680        backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-line"));
681        backend.draw_line(
682            &[
683                (right_x, plot_area.y),
684                (right_x, plot_area.y + plot_area.height),
685            ],
686            &LineStyle {
687                color: axis_line.color,
688                width: axis_line.width,
689                alpha: 1.0,
690                linetype: axis_line.linetype.clone(),
691                ..Default::default()
692            },
693        )?;
694    }
695
696    // Ticks and labels at primary break positions, but with transformed labels
697    for (pos, label) in &breaks {
698        let py = along_y(coord, *pos, plot_area);
699
700        if axis_ticks.visible {
701            backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-tick"));
702            backend.draw_line(
703                &[(right_x, py), (right_x + tick_len, py)],
704                &LineStyle {
705                    color: axis_ticks.color,
706                    width: axis_ticks.width,
707                    alpha: 1.0,
708                    linetype: axis_ticks.linetype.clone(),
709                    ..Default::default()
710                },
711            )?;
712        }
713
714        if theme.axis_text_y.visible {
715            // Parse the primary label back to a number, transform it
716            let locale = primary_scale.locale();
717            let parsed = match locale {
718                Some(l) => l.parse_number(label),
719                None => label.parse::<f64>().ok(),
720            };
721            let sec_label = if own_ticks.is_some() {
722                label.clone()
723            } else if let Some(v) = parsed {
724                sec_axis.label(sec_axis.transform_value(v), locale)
725            } else {
726                label.clone()
727            };
728
729            let family = if theme.axis_text_y.family.is_empty() {
730                None
731            } else {
732                Some(theme.axis_text_y.family.clone())
733            };
734            backend.set_element_class(Some("gg-axis gg-axis-y gg-axis-text"));
735            backend.draw_text(
736                &sec_label,
737                (right_x + tick_len + theme.legend_spacing, py),
738                &TextStyle {
739                    color: theme.axis_text_y.color,
740                    size: theme.axis_text_y.size,
741                    anchor: TextAnchor::Start,
742                    angle: theme.axis_text_y.angle,
743                    family,
744                    face: theme.axis_text_y.face,
745                    bg_colour: None,
746                    bg_r: 0.0,
747                },
748            )?;
749        }
750    }
751
752    // Secondary axis title
753    if !sec_axis.name.is_empty() && theme.axis_title_y.visible {
754        // Clear the widest tick label (own percent ticks can exceed the
755        // 3.5-character default).
756        let max_ch = own_ticks
757            .as_ref()
758            .and_then(|t| t.iter().map(|(_, l)| l.chars().count()).max())
759            .unwrap_or(0);
760        let text_w =
761            (max_ch as f64 * theme.axis_text_y.size * 0.6).max(theme.axis_text_y.size * 3.5);
762        let title_x = right_x + tick_len + text_w + theme.legend_spacing;
763        let center_y = plot_area.y + plot_area.height / 2.0;
764        let family = if theme.axis_title_y.family.is_empty() {
765            None
766        } else {
767            Some(theme.axis_title_y.family.clone())
768        };
769        backend.set_element_class(Some("gg-axis-title gg-axis-title-y"));
770        crate::render::rich::draw(
771            backend,
772            theme.rich_text,
773            &sec_axis.name,
774            (title_x, center_y),
775            &TextStyle {
776                color: theme.axis_title_y.color,
777                size: theme.axis_title_y.size,
778                anchor: TextAnchor::Middle,
779                angle: 90.0,
780                family,
781                face: theme.axis_title_y.face,
782                bg_colour: None,
783                bg_r: 0.0,
784            },
785        )?;
786    }
787
788    Ok(())
789}
790
791/// The labels a secondary axis draws at `breaks` (its own ticks, or the
792/// primary labels run through the transform).
793fn sec_labels(
794    primary_scale: &dyn Scale,
795    sec_axis: &crate::scale::sec_axis::SecAxis,
796    breaks: &[(f64, String)],
797    own: bool,
798) -> Vec<String> {
799    let locale = primary_scale.locale();
800    breaks
801        .iter()
802        .map(|(_, label)| {
803            if own {
804                return label.clone();
805            }
806            let parsed = match locale {
807                Some(l) => l.parse_number(label),
808                None => label.parse::<f64>().ok(),
809            };
810            match parsed {
811                Some(v) => sec_axis.label(sec_axis.transform_value(v), locale),
812                None => label.clone(),
813            }
814        })
815        .collect()
816}
817
818/// The height a secondary x axis takes above the panel: ticks, one line of
819/// labels and its title (#409). Shared by the layout reservation and
820/// [`draw_sec_x_axis`].
821pub(crate) fn sec_x_axis_height(theme: &Theme, sec_axis: &crate::scale::sec_axis::SecAxis) -> f64 {
822    theme.ticks_len_x()
823        + if theme.axis_text_x.visible {
824            theme.axis_text_x.size + 4.0
825        } else {
826            0.0
827        }
828        + if !sec_axis.name.is_empty() && theme.axis_title_x.visible {
829            theme.axis_title_x.size + 6.0
830        } else {
831            0.0
832        }
833}
834
835/// Draw a secondary x axis along the top of the panel (ggplot2's
836/// `scale_x_continuous(sec.axis = …)` / `dup_axis()`, #409).
837pub fn draw_sec_x_axis(
838    primary_scale: &dyn Scale,
839    sec_axis: &crate::scale::sec_axis::SecAxis,
840    coord: &dyn Coord,
841    theme: &Theme,
842    plot_area: &Rect,
843    backend: &mut dyn DrawBackend,
844) -> Result<(), RenderError> {
845    let own_ticks = sec_axis.own_ticks(primary_scale);
846    let breaks = own_ticks.clone().unwrap_or_else(|| primary_scale.breaks());
847    let labels = sec_labels(primary_scale, sec_axis, &breaks, own_ticks.is_some());
848    let tick_len = theme.ticks_len_x();
849    let axis_line = theme.axis_line_at(crate::theme::AxisSide::Top);
850    let axis_ticks = theme.axis_ticks_at(crate::theme::AxisSide::Top);
851    let top_y = plot_area.y;
852    let line = |el: &crate::theme::elements::ElementLine| LineStyle {
853        color: el.color,
854        width: el.width,
855        alpha: 1.0,
856        linetype: el.linetype.clone(),
857        ..Default::default()
858    };
859    if axis_line.visible {
860        backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-line"));
861        backend.draw_line(
862            &[(plot_area.x, top_y), (plot_area.x + plot_area.width, top_y)],
863            &line(axis_line),
864        )?;
865    }
866    let family = |f: &str| (!f.is_empty()).then(|| f.to_string());
867    for ((pos, _), label) in breaks.iter().zip(&labels) {
868        let px = along_x(coord, *pos, plot_area);
869        if axis_ticks.visible {
870            backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-tick"));
871            backend.draw_line(&[(px, top_y), (px, top_y - tick_len)], &line(axis_ticks))?;
872        }
873        if theme.axis_text_x.visible {
874            backend.set_element_class(Some("gg-axis gg-axis-x gg-axis-text"));
875            backend.draw_text(
876                label,
877                (px, top_y - tick_len - 2.0 - theme.axis_text_x.size / 2.0),
878                &TextStyle {
879                    color: theme.axis_text_x.color,
880                    size: theme.axis_text_x.size,
881                    anchor: TextAnchor::Middle,
882                    angle: 0.0,
883                    family: family(&theme.axis_text_x.family),
884                    face: theme.axis_text_x.face,
885                    bg_colour: None,
886                    bg_r: 0.0,
887                },
888            )?;
889        }
890    }
891    if !sec_axis.name.is_empty() && theme.axis_title_x.visible {
892        let y = top_y - sec_x_axis_height(theme, sec_axis) + theme.axis_title_x.size / 2.0;
893        backend.set_element_class(Some("gg-axis-title gg-axis-title-x"));
894        crate::render::rich::draw(
895            backend,
896            theme.rich_text,
897            &sec_axis.name,
898            (plot_area.x + plot_area.width / 2.0, y),
899            &TextStyle {
900                color: theme.axis_title_x.color,
901                size: theme.axis_title_x.size,
902                anchor: TextAnchor::Middle,
903                angle: 0.0,
904                family: family(&theme.axis_title_x.family),
905                face: theme.axis_title_x.face,
906                bg_colour: None,
907                bg_r: 0.0,
908            },
909        )?;
910    }
911    Ok(())
912}
913
914/// Compute minor break positions as midpoints between major breaks.
915fn minor_breaks(major: &[(f64, String)]) -> Vec<f64> {
916    if major.len() < 2 {
917        return vec![];
918    }
919    let mut minors = Vec::with_capacity(major.len() - 1);
920    for pair in major.windows(2) {
921        minors.push((pair[0].0 + pair[1].0) / 2.0);
922    }
923    minors
924}
925
926/// Draw gridlines for both axes.
927pub fn draw_gridlines(
928    x_scale: &dyn Scale,
929    y_scale: &dyn Scale,
930    coord: &dyn Coord,
931    theme: &Theme,
932    plot_area: &Rect,
933    backend: &mut dyn DrawBackend,
934) -> Result<(), RenderError> {
935    let major_x = theme.get_panel_grid_major_x();
936    let major_y = theme.get_panel_grid_major_y();
937    let minor_x = theme.get_panel_grid_minor_x();
938    let minor_y = theme.get_panel_grid_minor_y();
939
940    let x_breaks = x_scale.breaks();
941    let y_breaks = y_scale.breaks();
942
943    // Minor X gridlines (vertical) — drawn first so majors paint over them
944    if minor_x.visible {
945        for pos in minor_breaks(&x_breaks) {
946            let px = along_x(coord, pos, plot_area);
947            backend.set_element_class(Some("gg-grid gg-grid-minor gg-grid-x"));
948            backend.draw_line(
949                &[(px, plot_area.y), (px, plot_area.y + plot_area.height)],
950                &LineStyle {
951                    color: minor_x.color,
952                    width: minor_x.width,
953                    alpha: 1.0,
954                    linetype: minor_x.linetype.clone(),
955                    ..Default::default()
956                },
957            )?;
958        }
959    }
960
961    // Minor Y gridlines (horizontal)
962    if minor_y.visible {
963        for pos in minor_breaks(&y_breaks) {
964            let py = along_y(coord, pos, plot_area);
965            backend.set_element_class(Some("gg-grid gg-grid-minor gg-grid-y"));
966            backend.draw_line(
967                &[(plot_area.x, py), (plot_area.x + plot_area.width, py)],
968                &LineStyle {
969                    color: minor_y.color,
970                    width: minor_y.width,
971                    alpha: 1.0,
972                    linetype: minor_y.linetype.clone(),
973                    ..Default::default()
974                },
975            )?;
976        }
977    }
978
979    // Major X gridlines (vertical)
980    if major_x.visible {
981        for (pos, _) in &x_breaks {
982            let px = along_x(coord, *pos, plot_area);
983            backend.set_element_class(Some("gg-grid gg-grid-major gg-grid-x"));
984            backend.draw_line(
985                &[(px, plot_area.y), (px, plot_area.y + plot_area.height)],
986                &LineStyle {
987                    color: major_x.color,
988                    width: major_x.width,
989                    alpha: 1.0,
990                    linetype: major_x.linetype.clone(),
991                    ..Default::default()
992                },
993            )?;
994        }
995    }
996
997    // Major Y gridlines (horizontal)
998    if major_y.visible {
999        for (pos, _) in &y_breaks {
1000            let py = along_y(coord, *pos, plot_area);
1001            backend.set_element_class(Some("gg-grid gg-grid-major gg-grid-y"));
1002            backend.draw_line(
1003                &[(plot_area.x, py), (plot_area.x + plot_area.width, py)],
1004                &LineStyle {
1005                    color: major_y.color,
1006                    width: major_y.width,
1007                    alpha: 1.0,
1008                    linetype: major_y.linetype.clone(),
1009                    ..Default::default()
1010                },
1011            )?;
1012        }
1013    }
1014
1015    Ok(())
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020    use super::*;
1021    use crate::aes::Aesthetic;
1022    use crate::coord::cartesian::CoordCartesian;
1023    use crate::data::Value;
1024    use crate::render::svg_backend::SvgBackend;
1025    use crate::theme::presets::theme_gray;
1026
1027    /// A scale with hand-picked break positions/labels, so a test can place
1028    /// one off the canvas without fighting a real break algorithm.
1029    struct FixedBreaksScale(Vec<(f64, String)>);
1030
1031    impl Scale for FixedBreaksScale {
1032        fn aesthetic(&self) -> Aesthetic {
1033            Aesthetic::X
1034        }
1035        fn train(&mut self, _values: &[Value]) {}
1036        fn map(&self, _value: &Value) -> f64 {
1037            0.0
1038        }
1039        fn breaks(&self) -> Vec<(f64, String)> {
1040            self.0.clone()
1041        }
1042        fn name(&self) -> &str {
1043            ""
1044        }
1045        fn set_name(&mut self, _name: &str) {}
1046        fn clone_box(&self) -> Box<dyn Scale> {
1047            Box::new(FixedBreaksScale(self.0.clone()))
1048        }
1049    }
1050
1051    fn backend(w: u32, h: u32, plot_area: Rect) -> SvgBackend {
1052        SvgBackend::new(w, h, plot_area)
1053    }
1054
1055    #[test]
1056    fn a_tick_outside_the_svg_is_dropped() {
1057        // Normalized position 5.0 is nowhere near [0, 1]; through
1058        // `CoordCartesian` that lands far outside the 200×100 canvas.
1059        let scale = FixedBreaksScale(vec![
1060            (0.2, "kept".to_string()),
1061            (5.0, "off_canvas".to_string()),
1062        ]);
1063        let coord = CoordCartesian::new();
1064        let theme = theme_gray();
1065        let plot_area = Rect {
1066            x: 10.0,
1067            y: 10.0,
1068            width: 180.0,
1069            height: 70.0,
1070        };
1071        let canvas = Rect {
1072            x: 0.0,
1073            y: 0.0,
1074            width: 200.0,
1075            height: 100.0,
1076        };
1077        let mut backend = backend(200, 100, plot_area.clone());
1078        draw_x_axis(&scale, &coord, &theme, &plot_area, &canvas, &mut backend).unwrap();
1079        let svg = backend.finish();
1080        assert!(svg.contains(">kept<"), "on-canvas label dropped: {svg}");
1081        assert!(
1082            !svg.contains(">off_canvas<"),
1083            "off-canvas label was drawn: {svg}"
1084        );
1085    }
1086
1087    #[test]
1088    fn clip_draws_the_label_exactly_at_the_tick_even_past_the_edge() {
1089        // A very wide label at the rightmost tick, Clip mode: no shift.
1090        let scale = FixedBreaksScale(vec![
1091            (0.0, "a".to_string()),
1092            (1.0, "2021-01-01".to_string()),
1093        ]);
1094        let coord = CoordCartesian::new();
1095        let mut theme = theme_gray();
1096        theme.axis_text_x_fit = crate::theme::AxisLabelFit::Clip;
1097        let plot_area = Rect {
1098            x: 0.0,
1099            y: 0.0,
1100            width: 60.0,
1101            height: 50.0,
1102        };
1103        let canvas = plot_area.clone();
1104        let mut backend = backend(60, 50, plot_area.clone());
1105        draw_x_axis(&scale, &coord, &theme, &plot_area, &canvas, &mut backend).unwrap();
1106        let svg = backend.finish();
1107        // Clip: the label sits exactly on the tick (x="60.00"), unmoved,
1108        // even though its bbox clearly overflows a 60px canvas.
1109        assert!(
1110            svg.contains("x=\"60.00\" y=\"") && svg.contains(">2021-01-01<"),
1111            "clip mode should not shift the label: {svg}"
1112        );
1113    }
1114
1115    #[test]
1116    fn shift_moves_the_same_label_inside_the_canvas() {
1117        let scale = FixedBreaksScale(vec![
1118            (0.0, "a".to_string()),
1119            (1.0, "2021-01-01".to_string()),
1120        ]);
1121        let coord = CoordCartesian::new();
1122        let mut theme = theme_gray();
1123        theme.axis_text_x_fit = crate::theme::AxisLabelFit::Shift;
1124        let plot_area = Rect {
1125            x: 0.0,
1126            y: 0.0,
1127            width: 60.0,
1128            height: 50.0,
1129        };
1130        let canvas = plot_area.clone();
1131        let mut backend = backend(60, 50, plot_area.clone());
1132        draw_x_axis(&scale, &coord, &theme, &plot_area, &canvas, &mut backend).unwrap();
1133        let svg = backend.finish();
1134        assert!(
1135            !svg.contains("x=\"60.00\" y=\""),
1136            "shift mode should move the label off the bare tick: {svg}"
1137        );
1138        let w = crate::render::text::text_width("2021-01-01", theme.axis_text_x.size);
1139        // The shifted label's right edge must land inside the canvas.
1140        let needle = ">2021-01-01<";
1141        let tag_end = svg.find(needle).unwrap();
1142        let tag_start = svg[..tag_end].rfind("<text ").unwrap();
1143        let tag = &svg[tag_start..tag_end];
1144        let x_attr = tag.rsplit("x=\"").next().unwrap();
1145        let x: f64 = x_attr.split('"').next().unwrap().parse().unwrap();
1146        // `x` round-trips through a `"{:.2}"`-formatted SVG attribute, so
1147        // allow a hair of slack for that rounding.
1148        assert!(
1149            x + w / 2.0 <= 60.0 - 1.0 + 0.01,
1150            "right edge still overflows: x={x} w={w}"
1151        );
1152    }
1153}
1154
1155#[cfg(test)]
1156mod fit_label_538_tests {
1157    use super::fit_label;
1158
1159    #[test]
1160    fn a_label_is_kept_shortened_or_reduced_to_an_ellipsis() {
1161        // fits, or no room to speak of: as it was
1162        assert_eq!(fit_label("ES_bu", 11.0, 200.0), "ES_bu");
1163        assert_eq!(fit_label("a long label", 11.0, 5.0), "a long label");
1164        // too wide: shortened, trailing space trimmed before the ellipsis
1165        let cut = fit_label("one global model (anofox_ml)", 11.0, 60.0);
1166        assert!(
1167            cut.ends_with('…') && cut.len() < "one global model (anofox_ml)".len(),
1168            "{cut}"
1169        );
1170        assert!(!cut.contains(" …"), "{cut}");
1171        // room for the ellipsis only
1172        assert_eq!(fit_label("WWWWWWWW", 11.0, 11.5), "…");
1173    }
1174}