plotters-rs / plotters

A rust drawing library for high quality data plotting for both WASM and native, statically and realtimely 🦀 📈🚀
https://plotters-rs.github.io/home/
MIT License
3.88k stars 281 forks source link

[BUG] SVGBackend with Histograms fails silently when drawing data series #470

Open pbdeuchler opened 1 year ago

pbdeuchler commented 1 year ago

Describe the bug The SVGBackend with Histograms fails to draw the actual chart content and does so without errors. I believe there's something going on with the types, but i'm not sure.

To Reproduce This reproduces consistently: broken

use plotters::prelude::*;

const HISTOGRAM_OUT_FILE: &'static str = "plots/broken.svg";

fn main() {
    let path = HISTOGRAM_OUT_FILE;
    let root = SVGBackend::new(path, (2048, 1536)).into_drawing_area();

    root.fill(&WHITE).unwrap();

    let mut chart = ChartBuilder::on(&root)
        .x_label_area_size(35)
        .y_label_area_size(40)
        .margin(5)
        .caption("SVG Broken", ("sans-serif", 50.0))
        .build_cartesian_2d(
            (0i32..450i32).into_segmented(),
            0i32..10i32,
        )
        .unwrap();

    chart
        .configure_mesh()
        .disable_x_mesh()
        .bold_line_style(&WHITE.mix(0.3))
        .y_desc("Count")
        .x_desc("Bucket")
        .axis_desc_style(("sans-serif", 15))
        .draw()
        .unwrap();

    let data_series: Vec<(i32, i32)> = Vec::from([(123 as i32, 1 as i32)]);

    chart
        .draw_series(
            Histogram::vertical(&chart)
                .style(RED.mix(0.5).filled())
                .data(data_series),
        )
        .unwrap();

    // To avoid the IO failure being ignored silently, we manually call the present function
    root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir");
    println!("Result has been saved to {}", path);
}

Version Information plotters = "^0.3.1" rust nightly

ozwaldorf commented 1 year ago

Happened upon this bug while using plotters for a project. Would be nice to see it fixed!

AliMMehr commented 1 year ago

If you set the Histogram margin to a small value, e.g. 0, it works:

chart
        .draw_series(
            Histogram::vertical(&chart)
                .margin(0)    // This is the new line that I added
                .style(RED.mix(0.5).filled())
                .data(data_series),
        )
        .unwrap();

I think there needs to be an error for when the margin of the rectangle is bigger than its width which can cause some unexpected behavior (e.g. sometimes the rectangle is not drawn)