plotlib/repr/
barchart.rs

1/*!
2
3Bar chart
4
5# Examples
6
7```
8# use plotlib::repr::BarChart;
9# use plotlib::view::CategoricalView;
10let b1 = BarChart::new(5.2).label("b1");
11let b2 = BarChart::new(1.6).label("b2");
12let v = CategoricalView::new().add(b1).add(b2);
13```
14*/
15
16use std::f64;
17
18use svg;
19
20use crate::axis;
21use crate::repr::CategoricalRepresentation;
22use crate::style::BoxStyle;
23use crate::svg_render;
24
25pub struct BarChart {
26    value: f64,
27    label: String,
28    style: BoxStyle,
29}
30
31impl BarChart {
32    pub fn new(v: f64) -> Self {
33        BarChart {
34            value: v,
35            style: BoxStyle::new(),
36            label: String::new(),
37        }
38    }
39
40    pub fn style(mut self, style: &BoxStyle) -> Self {
41        self.style.overlay(style);
42        self
43    }
44
45    pub fn get_style(&self) -> &BoxStyle {
46        &self.style
47    }
48
49    pub fn label<T>(mut self, label: T) -> Self
50    where
51        T: Into<String>,
52    {
53        self.label = label.into();
54        self
55    }
56
57    pub fn get_label(&self) -> &String {
58        &self.label
59    }
60
61    fn get_value(&self) -> f64 {
62        self.value
63    }
64}
65
66impl CategoricalRepresentation for BarChart {
67    /// The maximum range. Used for auto-scaling axis
68    fn range(&self) -> (f64, f64) {
69        (0.0, self.value)
70    }
71
72    /// The ticks that this representation covers. Used to collect all ticks for display
73    fn ticks(&self) -> Vec<String> {
74        vec![self.label.clone()]
75    }
76
77    fn to_svg(
78        &self,
79        x_axis: &axis::CategoricalAxis,
80        y_axis: &axis::ContinuousAxis,
81        face_width: f64,
82        face_height: f64,
83    ) -> svg::node::element::Group {
84        svg_render::draw_face_barchart(
85            self.get_value(),
86            &self.label,
87            x_axis,
88            y_axis,
89            face_width,
90            face_height,
91            &self.style,
92        )
93    }
94
95    fn to_text(
96        &self,
97        _x_axis: &axis::CategoricalAxis,
98        _y_axis: &axis::ContinuousAxis,
99        _face_width: u32,
100        _face_height: u32,
101    ) -> String {
102        "".into()
103    }
104}