Skip to main content

ggplot_rs/render/
direct_labels.rs

1//! Direct labels (#543, R's `directlabels` / a `ggrepel` label at the last
2//! point): instead of a colour legend, each line's colour group is named at
3//! its end, in its own colour, in the band right of the panel that a right
4//! legend would take. Labels never overlap: they are pushed apart vertically
5//! (in order of their line's end), then kept inside the panel's height; a
6//! label moved away from its line's end gets a short leader to it.
7
8use crate::aes::Aesthetic;
9use crate::build::BuiltPlot;
10use crate::render::backend::{DrawBackend, LineStyle, TextAnchor, TextStyle};
11use crate::render::Rect;
12use crate::render::RenderError;
13
14/// One label: its line's end (px), its text and colour.
15struct End {
16    x: f64,
17    y: f64,
18    text: String,
19    color: (u8, u8, u8),
20}
21
22/// The line layers' group ends, or `None` when nothing can be labelled this
23/// way (no line layer with a mapped colour) — the caller then draws the usual
24/// legend.
25fn ends(built: &BuiltPlot, plot_area: &Rect) -> Option<Vec<End>> {
26    let (xs, ys) = (
27        built.scales.get(&Aesthetic::X)?,
28        built.scales.get(&Aesthetic::Y)?,
29    );
30    let mut out: Vec<End> = Vec::new();
31    for layer in &built.layers {
32        if !matches!(layer.geom.name(), "line" | "path" | "step") {
33            continue;
34        }
35        let data = &layer.data;
36        let (Some(color), Some(x), Some(y)) =
37            (data.column("color"), data.column("x"), data.column("y"))
38        else {
39            continue;
40        };
41        // the row with the largest x per colour level
42        let mut last: Vec<(String, usize, f64)> = Vec::new();
43        for i in 0..data.nrows() {
44            let (nx, ny) = (xs.map(&x[i]), ys.map(&y[i]));
45            if !nx.is_finite() || !ny.is_finite() {
46                continue;
47            }
48            let key = crate::geom::tip_value(&color[i]);
49            match last.iter_mut().find(|(k, ..)| *k == key) {
50                Some(e) if nx > e.2 => (e.1, e.2) = (i, nx),
51                Some(_) => {}
52                None => last.push((key, i, nx)),
53            }
54        }
55        for (text, i, _) in last {
56            if out.iter().any(|e| e.text == text) {
57                continue;
58            }
59            let (px, py) = built
60                .coord
61                .transform((xs.map(&x[i]), ys.map(&y[i])), plot_area);
62            let color = built
63                .scales
64                .map_color(&Aesthetic::Color, &color[i])
65                .unwrap_or((60, 60, 60));
66            out.push(End {
67                x: px,
68                y: py,
69                text,
70                color,
71            });
72        }
73    }
74    (!out.is_empty()).then_some(out)
75}
76
77/// Spread label centres `ys` (sorted ascending) at least `gap` apart and keep
78/// them within `[lo, hi]`, moving each as little as possible.
79fn spread(ys: &mut [f64], gap: f64, lo: f64, hi: f64) {
80    if ys.is_empty() {
81        return;
82    }
83    let n = ys.len();
84    // if they can't all fit, squeeze the gap
85    let gap = gap
86        .min(if n > 1 {
87            (hi - lo) / (n - 1) as f64
88        } else {
89            gap
90        })
91        .max(0.0);
92    for _ in 0..50 {
93        let mut moved = false;
94        for i in 1..n {
95            let d = ys[i] - ys[i - 1];
96            if d < gap - 1e-9 {
97                let push = (gap - d) / 2.0;
98                ys[i - 1] -= push;
99                ys[i] += push;
100                moved = true;
101            }
102        }
103        if ys[0] < lo {
104            let s = lo - ys[0];
105            ys.iter_mut().for_each(|y| *y += s);
106            moved = true;
107        }
108        if ys[n - 1] > hi {
109            let s = ys[n - 1] - hi;
110            ys.iter_mut().for_each(|y| *y -= s);
111            moved = true;
112        }
113        if !moved {
114            break;
115        }
116    }
117}
118
119/// Draw the direct labels; `Ok(false)` when there is nothing to label this
120/// way (the caller draws the legend instead).
121pub fn draw(
122    built: &BuiltPlot,
123    plot_area: &Rect,
124    backend: &mut dyn DrawBackend,
125) -> Result<bool, RenderError> {
126    let Some(mut ends) = ends(built, plot_area) else {
127        return Ok(false);
128    };
129    let theme = &built.theme;
130    let size = theme.legend_text.size;
131    ends.sort_by(|a, b| a.y.total_cmp(&b.y));
132    let mut ys: Vec<f64> = ends.iter().map(|e| e.y).collect();
133    spread(
134        &mut ys,
135        size * 1.35,
136        plot_area.y + size * 0.6,
137        plot_area.y + plot_area.height - size * 0.6,
138    );
139    let x0 = plot_area.x + plot_area.width;
140    let tx = x0 + theme.legend_spacing.max(6.0);
141    backend.set_element_class(Some("gg-direct-label"));
142    for (e, y) in ends.iter().zip(&ys) {
143        // a label away from its line's end gets a leader to it
144        if (y - e.y).abs() > size * 0.3 || e.x < x0 - 1.0 {
145            backend.draw_line(
146                &[(e.x + 2.0, e.y), (tx - 2.0, *y)],
147                &LineStyle {
148                    color: e.color,
149                    width: 0.6,
150                    alpha: 0.6,
151                    ..Default::default()
152                },
153            )?;
154        }
155        backend.set_mark_series(Some(e.text.clone()));
156        backend.draw_text(
157            &e.text,
158            (tx, *y),
159            &TextStyle {
160                color: e.color,
161                size,
162                anchor: TextAnchor::Start,
163                ..Default::default()
164            },
165        )?;
166        backend.set_mark_series(None);
167    }
168    backend.set_element_class(None);
169    Ok(true)
170}
171
172#[cfg(test)]
173mod tests {
174    use super::spread;
175
176    #[test]
177    fn labels_are_pushed_apart_and_kept_in_range() {
178        let mut ys = vec![10.0, 11.0, 12.0, 50.0];
179        spread(&mut ys, 5.0, 0.0, 100.0);
180        assert!(ys.windows(2).all(|w| w[1] - w[0] >= 5.0 - 1e-6), "{ys:?}");
181        assert!(
182            (ys[3] - 50.0).abs() < 1e-9,
183            "a label with room stays put: {ys:?}"
184        );
185        let mut low = vec![0.0, 0.5];
186        spread(&mut low, 5.0, 2.0, 100.0);
187        assert!(
188            low[0] >= 2.0 - 1e-9 && low[1] - low[0] >= 5.0 - 1e-6,
189            "{low:?}"
190        );
191    }
192}