Skip to main content

ggplot_rs/coord/
fixed.rs

1use crate::render::Rect;
2
3use super::Coord;
4
5/// Fixed-ratio coordinate system — maintains aspect ratio.
6pub struct CoordFixed {
7    pub ratio: f64,
8}
9
10impl CoordFixed {
11    pub fn new(ratio: f64) -> Self {
12        CoordFixed { ratio }
13    }
14}
15
16impl Coord for CoordFixed {
17    fn transform(&self, point: (f64, f64), plot_area: &Rect) -> (f64, f64) {
18        // Compute the effective area that maintains the aspect ratio
19        let data_aspect = self.ratio; // data units_y / units_x
20        let pixel_aspect = plot_area.height / plot_area.width;
21
22        let (eff_w, eff_h, off_x, off_y) = if pixel_aspect > data_aspect {
23            // Too tall — use full width, reduce height
24            let h = plot_area.width * data_aspect;
25            (plot_area.width, h, 0.0, (plot_area.height - h) / 2.0)
26        } else {
27            // Too wide — use full height, reduce width
28            let w = plot_area.height / data_aspect;
29            (w, plot_area.height, (plot_area.width - w) / 2.0, 0.0)
30        };
31
32        let (nx, ny) = point;
33        let px = plot_area.x + off_x + nx * eff_w;
34        let py = plot_area.y + off_y + (1.0 - ny) * eff_h;
35        (px, py)
36    }
37}