stacked_horizontal_bar_chart/
stacked_horizontal_bar_chart.rs

1use charts::{Chart, HorizontalBarView, ScaleBand, ScaleLinear, BarLabelPosition};
2
3fn main() {
4    // Define chart related sizes.
5    let width = 800;
6    let height = 600;
7    let (top, right, bottom, left) = (90, 40, 50, 60);
8
9    // Create a linear scale that will interpolate values in [0, 100] range to corresponding
10    // values in [0, availableWidth] range (the width of the chart without the margins).
11    let x = ScaleLinear::new()
12        .set_domain(vec![0_f32, 100_f32])
13        .set_range(vec![0, width - left - right]);
14
15    // Create a band scale that maps ["A", "B", "C"] categories to values in the [0, availableHeight]
16    // range (the height of the chart without the margins).
17    let y = ScaleBand::new()
18        .set_domain(vec![String::from("A"), String::from("B"), String::from("C")])
19        .set_range(vec![0, height - top - bottom]);
20
21    // You can use your own iterable as data as long as its items implement the `BarDatum` trait.
22    let data = vec![("A", 70, "foo"), ("B", 10, "foo"), ("C", 30, "foo"), ("A", 20, "bar"), ("A", 5, "baz")];
23
24    // Create VerticalBar view that is going to represent the data as vertical bars.
25    let view = HorizontalBarView::new()
26        .set_x_scale(&x)
27        .set_y_scale(&y)
28        .set_label_position(BarLabelPosition::Center)
29        .load_data(&data).unwrap();
30
31    // Generate and save the chart.
32    Chart::new()
33        .set_width(width)
34        .set_height(height)
35        .set_margins(top, right, bottom, left)
36        .add_title(String::from("Horizontal Stacked Bar Chart"))
37        .add_view(&view)
38        .add_axis_bottom(&x)
39        .add_axis_left(&y)
40        .add_left_axis_label("Y Axis Custom Label")
41        .add_bottom_axis_label("X Axis Custom Label")
42        .save("stacked-horizontal-bar-chart.svg").unwrap();
43}