Skip to main content

ses_pdf/chart/
line.rs

1use plotters::prelude::*;
2use plotters_svg::SVGBackend;
3use serde::{Deserialize, Serialize};
4
5use super::color::{ChartColor, DEFAULT_PALETTE};
6use super::ChartError;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct LineChart {
10    pub title: String,
11    pub x_label: String,
12    pub y_label: String,
13    pub series: Vec<LineSeries>,
14    pub width: u32,
15    pub height: u32,
16    pub x_range: Option<(f64, f64)>,
17    pub y_range: Option<(f64, f64)>,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct LineSeries {
22    pub name: String,
23    pub points: Vec<(f64, f64)>,
24    pub color: Option<ChartColor>,
25}
26
27pub(crate) fn render_line(c: &LineChart) -> Result<String, ChartError> {
28    let mut buf = String::new();
29    {
30        let root = SVGBackend::with_string(&mut buf, (c.width, c.height)).into_drawing_area();
31        root.fill(&WHITE).map_err(|e| ChartError(e.to_string()))?;
32
33        let (x_min, x_max) = c.x_range.unwrap_or_else(|| auto_x_range(&c.series));
34        let (y_min, y_max) = c.y_range.unwrap_or_else(|| auto_y_range(&c.series));
35
36        let mut chart = ChartBuilder::on(&root)
37            .caption(&c.title, ("sans-serif", 18u32).into_font())
38            .margin(15u32)
39            .x_label_area_size(45u32)
40            .y_label_area_size(55u32)
41            .build_cartesian_2d(x_min..x_max, y_min..y_max)
42            .map_err(|e| ChartError(e.to_string()))?;
43
44        chart
45            .configure_mesh()
46            .x_desc(&c.x_label)
47            .y_desc(&c.y_label)
48            .draw()
49            .map_err(|e| ChartError(e.to_string()))?;
50
51        for (i, series) in c.series.iter().enumerate() {
52            let color: RGBColor = series
53                .color
54                .unwrap_or(DEFAULT_PALETTE[i % DEFAULT_PALETTE.len()])
55                .into();
56            let pts = series.points.clone();
57            let name = series.name.clone();
58            chart
59                .draw_series(plotters::series::LineSeries::new(
60                    pts,
61                    color.stroke_width(2),
62                ))
63                .map_err(|e| ChartError(e.to_string()))?
64                .label(name)
65                .legend(move |(x, y)| {
66                    PathElement::new(vec![(x, y), (x + 20, y)], color)
67                });
68        }
69
70        chart
71            .configure_series_labels()
72            .border_style(BLACK)
73            .background_style(WHITE.mix(0.8))
74            .draw()
75            .map_err(|e| ChartError(e.to_string()))?;
76
77        root.present().map_err(|e| ChartError(e.to_string()))?;
78    }
79    Ok(buf)
80}
81
82fn auto_x_range(series: &[LineSeries]) -> (f64, f64) {
83    let mut min = f64::MAX;
84    let mut max = f64::MIN;
85    for s in series {
86        for (x, _) in &s.points {
87            if *x < min {
88                min = *x;
89            }
90            if *x > max {
91                max = *x;
92            }
93        }
94    }
95    if min >= max {
96        (0.0, 1.0)
97    } else {
98        (min, max)
99    }
100}
101
102fn auto_y_range(series: &[LineSeries]) -> (f64, f64) {
103    let mut min = f64::MAX;
104    let mut max = f64::MIN;
105    for s in series {
106        for (_, y) in &s.points {
107            if *y < min {
108                min = *y;
109            }
110            if *y > max {
111                max = *y;
112            }
113        }
114    }
115    if min >= max {
116        (0.0, 1.0)
117    } else {
118        let pad = (max - min) * 0.05;
119        (min - pad, max + pad)
120    }
121}