vizkit 0.1.0

A rendering-agnostic kit for data visualization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use super::{Alignment, LineAttrs, LineProperties, Orientation, TextProperties};
use crate::chromatic::Color;
use crate::scale::Axis;

/// Axis options for properties related to tick lines and labels
pub struct AxisOptions {
    /// Size of tick lines
    pub tick_size: f32,
    /// Offset between tick lines and tick labels
    pub offset: f32,
    /// Number of ticks, it is passed to [`Axis::ticks`][`crate::scale::Axis::ticks`]
    pub count: Option<usize>,
    /// Line attributes
    pub line_attrs: LineAttrs,
    /// Text fill color
    pub text_fill_color: Color,
    /// Font size
    pub font_size: f32,
}

/// Axis placement information
struct AxisPlacement {
    /// Where the axis is located around its perpendicular direction
    at: f32,
    /// Orientation for flip (x, y) to (y, x)
    orientation: Orientation,
    /// Direction for adding or removing spaces (`tick_size` and `offset`)
    direction: f32,
    /// X-oriented text alignment
    align_x: Alignment,
    /// Y-oriented text alignment
    align_y: Alignment,
}

impl Default for AxisOptions {
    fn default() -> Self {
        Self {
            tick_size: 7.5,
            offset: 0.5,
            count: None,
            line_attrs: LineAttrs::default(),
            text_fill_color: Color::default(),
            font_size: 12.,
        }
    }
}

/// Creates an iterator for a top-oriented axis, positioning ticks above the horizontal domain line.
///
/// Returns an iterator of tuples containing tick lines and their corresponding labels.
///
/// # Example
///
/// ```
/// use vizkit::{
///     draw::{AxisOptions, LineProperties, TextProperties, axis_top_iter},
///     scale::{Axis, ScaleContinuous},
/// };
///
/// let width = 960.;
/// let height = 400.;
///
/// let margin_top = 10.;
/// let margin_left = 30.;
/// let margin_right = 20.;
///
/// let scaler = ScaleContinuous::linear()
///     .domain([0., 100.])
///     .range([margin_left, width - margin_right]);
///
/// let (tick_lines, tick_labels): (Vec<LineProperties>, Vec<TextProperties>) = axis_top_iter(
///     &scaler,
///     margin_top,
///     |tick| tick.to_string(),
///     &AxisOptions::default(),
/// ).unzip();
/// ```
pub fn axis_top_iter<A: Axis>(
    scaler: &A,
    y: f32,
    formatter: impl Fn(&A::Tick) -> String,
    axis_options: &AxisOptions,
) -> impl Iterator<Item = (LineProperties, TextProperties)> {
    axis(
        scaler,
        AxisPlacement {
            at: y,
            orientation: Orientation::Same,
            direction: -1.,
            align_x: Alignment::Center,
            align_y: Alignment::End,
        },
        formatter,
        axis_options,
    )
}

/// Creates an iterator for a right-oriented axis, positioning ticks to the right of the vertical
/// domain line.
///
/// Returns an iterator of tuples containing tick lines and their corresponding labels.
///
/// # Example
///
/// ```
/// use vizkit::{
///     draw::{AxisOptions, LineProperties, TextProperties, axis_right_iter},
///     scale::{Axis, ScaleContinuous},
/// };
///
/// let width = 960.;
/// let height = 400.;
///
/// let margin_top = 10.;
/// let margin_right = 20.;
/// let margin_bottom = 30.;
///
/// let scaler = ScaleContinuous::linear()
///     .domain([0., 100.])
///     .range([height - margin_bottom, margin_top]);
///
/// let (tick_lines, tick_labels): (Vec<LineProperties>, Vec<TextProperties>) = axis_right_iter(
///     &scaler,
///     width - margin_right,
///     |tick| tick.to_string(),
///     &AxisOptions::default(),
/// ).unzip();
/// ```
pub fn axis_right_iter<A: Axis>(
    scaler: &A,
    x: f32,
    formatter: impl Fn(&A::Tick) -> String,
    axis_options: &AxisOptions,
) -> impl Iterator<Item = (LineProperties, TextProperties)> {
    axis(
        scaler,
        AxisPlacement {
            at: x,
            orientation: Orientation::Flip,
            direction: 1.,
            align_x: Alignment::Start,
            align_y: Alignment::Center,
        },
        formatter,
        axis_options,
    )
}

/// Creates an iterator for a bottom-oriented axis, positioning ticks below the horizontal domain
/// line.
///
/// Returns an iterator of tuples containing tick lines and their corresponding labels.
///
/// # Example
///
/// ```
/// use vizkit::{
///     draw::{AxisOptions, LineProperties, TextProperties, axis_bottom_iter},
///     scale::{Axis, ScaleContinuous},
/// };
///
/// let width = 960.;
/// let height = 400.;
///
/// let margin_left = 30.;
/// let margin_right = 20.;
/// let margin_bottom = 30.;
///
/// let scaler = ScaleContinuous::linear()
///     .domain([0., 100.])
///     .range([margin_left, width - margin_right]);
///
/// let (tick_lines, tick_labels): (Vec<LineProperties>, Vec<TextProperties>) = axis_bottom_iter(
///     &scaler,
///     height - margin_bottom,
///     |tick| tick.to_string(),
///     &AxisOptions::default(),
/// ).unzip();
/// ```
pub fn axis_bottom_iter<A: Axis>(
    scaler: &A,
    y: f32,
    formatter: impl Fn(&A::Tick) -> String,
    axis_options: &AxisOptions,
) -> impl Iterator<Item = (LineProperties, TextProperties)> {
    axis(
        scaler,
        AxisPlacement {
            at: y,
            orientation: Orientation::Same,
            direction: 1.,
            align_x: Alignment::Center,
            align_y: Alignment::Start,
        },
        formatter,
        axis_options,
    )
}

/// Creates an iterator for a left-oriented axis, positioning ticks to the left of the vertical
/// domain line.
///
/// Returns an iterator of tuples containing tick lines and their corresponding labels.
///
/// # Example
///
/// ```
/// use vizkit::{
///     draw::{AxisOptions, LineProperties, TextProperties, axis_left_iter},
///     scale::{Axis, ScaleContinuous},
/// };
///
/// let width = 960.;
/// let height = 400.;
///
/// let margin_top = 10.;
/// let margin_left = 30.;
/// let margin_bottom = 30.;
///
/// let scaler = ScaleContinuous::linear()
///     .domain([0., 100.])
///     .range([height - margin_bottom, margin_top]);
///
/// let (tick_lines, tick_labels): (Vec<LineProperties>, Vec<TextProperties>) = axis_left_iter(
///     &scaler,
///     margin_left,
///     |tick| tick.to_string(),
///     &AxisOptions::default(),
/// ).unzip();
/// ```
pub fn axis_left_iter<A: Axis>(
    scaler: &A,
    x: f32,
    formatter: impl Fn(&A::Tick) -> String,
    axis_options: &AxisOptions,
) -> impl Iterator<Item = (LineProperties, TextProperties)> {
    axis(
        scaler,
        AxisPlacement {
            at: x,
            orientation: Orientation::Flip,
            direction: -1.,
            align_x: Alignment::End,
            align_y: Alignment::Center,
        },
        formatter,
        axis_options,
    )
}

/// Generic function for creating an iterator for drawing the tick lines and tick labels of an axis.
fn axis<A: Axis>(
    scaler: &A,
    placement: AxisPlacement,
    formatter: impl Fn(&A::Tick) -> String,
    axis_options: &AxisOptions,
) -> impl Iterator<Item = (LineProperties, TextProperties)> {
    let ticks = scaler.ticks(axis_options.count);
    let AxisPlacement {
        at,
        orientation,
        direction,
        align_x,
        align_y,
    } = placement;
    ticks.into_iter().map(move |tick| {
        let content = formatter(&tick);
        let pos = scaler.tick_position(tick);
        (
            LineProperties {
                start: orientation.apply(pos, at),
                end: orientation.apply(pos, at + direction * axis_options.tick_size),
                stroke_color: axis_options.line_attrs.stroke_color,
                stroke_width: axis_options.line_attrs.stroke_width,
                stroke_opacity: axis_options.line_attrs.stroke_opacity,
            },
            TextProperties {
                position: orientation.apply(
                    pos,
                    at + direction * (axis_options.tick_size + axis_options.offset),
                ),
                content,
                fill_color: axis_options.text_fill_color,
                font_size: axis_options.font_size,
                align_x: align_x.clone(),
                align_y: align_y.clone(),
            },
        )
    })
}

#[cfg(test)]
mod tests {
    use super::{axis_bottom_iter, axis_left_iter, axis_right_iter, axis_top_iter};
    use crate::draw::{AxisOptions, LineProperties, TextProperties};
    use crate::scale::{Axis, ScaleContinuous};
    use rstest::rstest;

    const WIDTH: f32 = 400.;
    const HEIGHT: f32 = 100.;

    const MARGIN_LEFT: f32 = 10.;
    const MARGIN_TOP: f32 = 10.;

    const XMAX: f32 = 50.;
    const YMAX: f32 = 50.;

    struct Expected {
        at: f32,
        start: f32,
        end: f32,
        position: f32,
    }

    impl Expected {
        fn new(at: f32, start: f32, end: f32, position: f32) -> Self {
            Self {
                at,
                start,
                end,
                position,
            }
        }
    }

    #[rstest]
    #[case(
        "bottom",
        0,
        [0., XMAX],
        [0., WIDTH],
        Expected::new(HEIGHT, HEIGHT, HEIGHT + 7.5, HEIGHT + 7.5 + 0.5)
    )]
    #[case(
        "top",
        0,
        [0., XMAX],
        [0., WIDTH],
        Expected::new(MARGIN_TOP, MARGIN_TOP, MARGIN_TOP - 7.5, MARGIN_TOP - 7.5 - 0.5)
    )]
    #[case(
        "left",
        1,
        [0., YMAX],
        [HEIGHT, 0.],
        Expected::new(MARGIN_LEFT, MARGIN_LEFT, MARGIN_LEFT - 7.5, MARGIN_LEFT - 7.5 - 0.5)
    )]
    #[case(
        "right",
        1,
        [0., YMAX],
        [HEIGHT, 0.],
        Expected::new(WIDTH, WIDTH, WIDTH + 7.5, WIDTH + 7.5 + 0.5)
    )]
    fn test_axis(
        #[case] title: &str,
        #[case] index: usize,
        #[case] domain: [f32; 2],
        #[case] range: [f32; 2],
        #[case] expected: Expected,
    ) {
        let at = expected.at;
        let start = expected.start;
        let end = expected.end;
        let position = expected.position;
        let scale = ScaleContinuous::linear().domain(domain).range(range);

        let formatter = |x: &f32| x.to_string();
        let options = AxisOptions::default();
        let (lines, texts): (Vec<LineProperties>, Vec<TextProperties>) = match title {
            "bottom" => axis_bottom_iter(&scale, at, formatter, &options).unzip(),
            "top" => axis_top_iter(&scale, at, formatter, &options).unzip(),
            "left" => axis_left_iter(&scale, at, formatter, &options).unzip(),
            "right" => axis_right_iter(&scale, at, formatter, &options).unzip(),
            _ => unreachable!(),
        };

        // Indices for x and y orientation.
        // if index is 0 => position = (x, y)
        // if index is 1 => position = (y, x)
        let a = index;
        let b = (index + 1) % 2;

        // Expected values
        let tick_fn = |&tick: &f32| scale.tick_position(tick);
        let scale_ticks: Vec<f32> = scale.ticks(None).iter().map(tick_fn).collect();
        let string_ticks: Vec<String> = scale.ticks(None).iter().map(ToString::to_string).collect();

        // Test line properties
        for (i, line) in lines.iter().enumerate() {
            assert_eq!(line.start[a], line.end[a], "{}", title);
            assert_eq!(line.start[b], start, "{}", title);
            assert_eq!(line.end[b], end, "{}", title);
            assert_eq!(line.start[a], scale_ticks[i], "{}", title);
        }

        // Test text properties
        for (i, text) in texts.iter().enumerate() {
            assert_eq!(text.position[b], position, "{}", title);
            assert_eq!(text.position[a], scale_ticks[i], "{}", title);
            assert_eq!(text.content, string_ticks[i], "{}", title);
        }
    }
}