use std::collections::HashSet;
use dioxus::prelude::*;
use super::super::format::js_number;
use super::super::frame::{ChartPresentation, plot_label, render_frame};
use super::super::model::{
ChartDatum, ChartDomain, ChartLabels, ChartSeries, ChartTone, format_with, summarize,
};
use super::super::scale::{
CategoryTick, CategoryTickOptions, TickFormatter, axis_domain, axis_padding, category_ticks,
chart_ticks, estimate_chart_label_width, format_ticks, scale_value,
};
use super::empty_status;
use crate::class::{Glass, compose};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum WaterfallChartKind {
#[default]
Delta,
Total,
}
#[derive(Clone, Debug, PartialEq)]
pub struct WaterfallChartDatum {
pub id: String,
pub label: String,
pub value: f64,
pub kind: WaterfallChartKind,
pub tone: Option<ChartTone>,
}
impl WaterfallChartDatum {
pub fn delta(id: impl Into<String>, label: impl Into<String>, value: f64) -> Self {
Self {
id: id.into(),
label: label.into(),
value,
kind: WaterfallChartKind::Delta,
tone: None,
}
}
pub fn total(id: impl Into<String>, label: impl Into<String>, value: f64) -> Self {
Self {
kind: WaterfallChartKind::Total,
..Self::delta(id, label, value)
}
}
#[must_use]
pub fn with_tone(mut self, tone: ChartTone) -> Self {
self.tone = Some(tone);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct HistogramBin {
pub start: f64,
pub end: f64,
pub count: f64,
pub label: Option<String>,
}
impl HistogramBin {
pub fn new(start: f64, end: f64, count: f64) -> Self {
Self {
start,
end,
count,
label: None,
}
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum HistogramFrequency {
#[default]
Count,
Density,
}
#[derive(Props, Clone, PartialEq)]
pub struct WaterfallChartProps {
#[props(default)]
pub data: Vec<WaterfallChartDatum>,
#[props(into)]
pub value_label: Option<String>,
pub format_value: Option<Callback<f64, String>>,
pub labels: Option<ChartLabels>,
#[props(default = true)]
pub show_table: bool,
#[props(into)]
pub heading: Option<String>,
#[props(into)]
pub description: Option<String>,
#[props(into)]
pub value: Option<String>,
#[props(into)]
pub summary: Option<String>,
#[props(into)]
pub caption: Option<String>,
#[props(default)]
pub presentation: ChartPresentation,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = figure)]
pub attributes: Vec<Attribute>,
}
#[derive(Props, Clone, PartialEq)]
pub struct HistogramProps {
#[props(default)]
pub bins: Vec<HistogramBin>,
#[props(default)]
pub frequency: HistogramFrequency,
#[props(default)]
pub tone: ChartTone,
#[props(into)]
pub value_label: Option<String>,
pub format_boundary: Option<Callback<f64, String>>,
pub format_value: Option<Callback<f64, String>>,
pub labels: Option<ChartLabels>,
#[props(default = true)]
pub show_table: bool,
#[props(into)]
pub heading: Option<String>,
#[props(into)]
pub description: Option<String>,
#[props(into)]
pub value: Option<String>,
#[props(into)]
pub summary: Option<String>,
#[props(into)]
pub caption: Option<String>,
#[props(default)]
pub presentation: ChartPresentation,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = figure)]
pub attributes: Vec<Attribute>,
}
const INTERVAL_PADDING_TOP: f64 = 16.0;
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct IntervalFrame {
pub(crate) width: f64,
pub(crate) height: f64,
pub(crate) axis_font_size: f64,
pub(crate) domain: ChartDomain,
pub(crate) ticks: Vec<f64>,
pub(crate) tick_labels: Vec<String>,
pub(crate) left: f64,
pub(crate) top: f64,
pub(crate) right: f64,
pub(crate) bottom: f64,
}
impl IntervalFrame {
fn new(
values: &[f64],
format_value: Option<&Callback<f64, String>>,
trailing_label: &str,
) -> Self {
let (width, height, font_size) = (640.0_f64, 320.0_f64, 24.0_f64);
let values: Vec<Option<f64>> = values.iter().copied().map(Some).collect();
let domain = axis_domain(&values, None, true);
let ticks = chart_ticks(domain);
let tick_labels = format_ticks(&ticks, format_value);
let left = (width - 64.0).min(axis_padding(&tick_labels, 44.0, None) * font_size / 12.0);
let trailing_reach =
(width / 5.0).min(estimate_chart_label_width(trailing_label, font_size) / 2.0 + 2.0);
Self {
width,
height,
axis_font_size: font_size,
domain,
ticks,
tick_labels,
left,
top: INTERVAL_PADDING_TOP,
right: width - 24f64.max(trailing_reach),
bottom: height - 48.0,
}
}
pub(crate) fn y(&self, value: f64) -> f64 {
scale_value(value, self.domain, self.bottom, self.top)
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct IntervalMark {
pub(crate) end: f64,
pub(crate) height: f64,
pub(crate) key: String,
pub(crate) label: String,
pub(crate) start: f64,
pub(crate) tone: ChartTone,
pub(crate) value: f64,
pub(crate) width: f64,
pub(crate) x: f64,
pub(crate) y: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct WaterfallConnector {
pub(crate) x1: f64,
pub(crate) x2: f64,
pub(crate) y: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct IntervalModel {
pub(crate) frame: IntervalFrame,
pub(crate) valid: bool,
pub(crate) marks: Vec<IntervalMark>,
pub(crate) category_ticks: Vec<CategoryTick>,
pub(crate) connectors: Vec<WaterfallConnector>,
pub(crate) density_counts: Option<Vec<f64>>,
pub(crate) format_boundary: Option<TickFormatter>,
}
fn waterfall_tone(step: &WaterfallChartDatum) -> ChartTone {
match (step.tone, step.kind) {
(Some(tone), _) => tone,
(None, WaterfallChartKind::Total) => ChartTone::Series1,
(None, WaterfallChartKind::Delta) if step.value < 0.0 => ChartTone::Series5,
(None, WaterfallChartKind::Delta) => ChartTone::Series2,
}
}
pub(crate) fn waterfall_geometry(
data: &[WaterfallChartDatum],
format_value: Option<&Callback<f64, String>>,
) -> IntervalModel {
let mut balance = 0.0;
let steps: Vec<(f64, f64)> = data
.iter()
.map(|datum| {
let (start, end) = match datum.kind {
WaterfallChartKind::Total => (0.0, datum.value),
WaterfallChartKind::Delta => (balance, balance + datum.value),
};
balance = end;
(start, end)
})
.collect();
let mut ids = HashSet::new();
let valid = data.iter().zip(&steps).all(|(datum, (_, end))| {
datum.value.is_finite() && end.is_finite() && ids.insert(datum.id.as_str())
});
let values: Vec<f64> = if valid {
steps
.iter()
.flat_map(|(start, end)| [*start, *end])
.collect()
} else {
Vec::new()
};
let frame = IntervalFrame::new(&values, format_value, "");
#[allow(clippy::cast_precision_loss)]
let band = (frame.right - frame.left) / steps.len().max(1) as f64;
let marks: Vec<IntervalMark> = if valid {
data.iter()
.zip(&steps)
.enumerate()
.map(|(index, (datum, (start, end)))| {
#[allow(clippy::cast_precision_loss)]
let x = frame.left + band * (index as f64 + 0.15);
IntervalMark {
end: *end,
height: (frame.y(*end) - frame.y(*start)).abs(),
key: datum.id.clone(),
label: datum.label.clone(),
start: *start,
tone: waterfall_tone(datum),
value: datum.value,
width: band * 0.7,
x,
y: frame.y(*start).min(frame.y(*end)),
}
})
.collect()
} else {
Vec::new()
};
let labels: Vec<&str> = marks.iter().map(|mark| mark.label.as_str()).collect();
let positions: Vec<f64> = marks.iter().map(|mark| mark.x + mark.width / 2.0).collect();
let ticks = category_ticks(
&labels,
CategoryTickOptions::new(frame.left, frame.right)
.bounds(0.0, frame.width)
.maximum_font_size(frame.axis_font_size)
.positions(&positions),
);
let connectors = marks
.windows(2)
.map(|pair| WaterfallConnector {
x1: pair[0].x + pair[0].width,
x2: pair[1].x,
y: frame.y(pair[0].end),
})
.collect();
IntervalModel {
frame,
valid,
marks,
category_ticks: ticks,
connectors,
density_counts: None,
format_boundary: None,
}
}
fn valid_bins(bins: &[HistogramBin], frequency: HistogramFrequency) -> bool {
let first_width = bins.first().map_or(0.0, |bin| bin.end - bin.start);
bins.iter().enumerate().all(|(index, bin)| {
let width = bin.end - bin.start;
if ![bin.start, bin.end, bin.count, width]
.iter()
.all(|value| value.is_finite())
|| width <= 0.0
|| bin.count < 0.0
{
return false;
}
if index > 0 && bin.start < bins[index - 1].end {
return false;
}
frequency == HistogramFrequency::Density
|| (width - first_width).abs() <= first_width.abs() * 1e-9
})
}
pub(crate) fn histogram_geometry(
input: &[HistogramBin],
frequency: HistogramFrequency,
tone: ChartTone,
format_boundary: Option<&Callback<f64, String>>,
format_value: Option<&Callback<f64, String>>,
) -> IntervalModel {
let finite_input = input
.iter()
.all(|bin| bin.start.is_finite() && bin.end.is_finite() && bin.count.is_finite());
let mut bins: Vec<HistogramBin> = if finite_input {
input.to_vec()
} else {
Vec::new()
};
bins.sort_by(|left, right| left.start.total_cmp(&right.start));
let value_for = |bin: &HistogramBin| match frequency {
HistogramFrequency::Density => bin.count / (bin.end - bin.start),
HistogramFrequency::Count => bin.count,
};
let finite = finite_input
&& valid_bins(&bins, frequency)
&& bins.iter().all(|bin| value_for(bin).is_finite());
let values: Vec<f64> = if finite {
bins.iter().map(value_for).collect()
} else {
Vec::new()
};
let mut boundaries: Vec<f64> = if finite {
bins.iter()
.flat_map(|bin| [bin.start, bin.end])
.map(|value| if value == 0.0 { 0.0 } else { value })
.collect()
} else {
Vec::new()
};
boundaries.sort_by(f64::total_cmp);
boundaries.dedup();
let boundary = TickFormatter::new(&boundaries, format_boundary);
let trailing_label = boundaries
.last()
.map_or_else(String::new, |value| boundary.format(*value));
let frame = IntervalFrame::new(&values, format_value, &trailing_label);
let x_domain = ChartDomain::new(
bins.first().map_or(0.0, |bin| bin.start),
bins.last().map_or(1.0, |bin| bin.end),
);
let x = |value: f64| scale_value(value, x_domain, frame.left, frame.right);
let marks: Vec<IntervalMark> = if finite {
bins.iter()
.map(|bin| {
let value = value_for(bin);
IntervalMark {
end: bin.end,
height: frame.y(0.0) - frame.y(value),
key: format!("number:{}", js_number(bin.start)),
label: bin.label.clone().unwrap_or_else(|| {
format!(
"{}–{}",
boundary.format(bin.start),
boundary.format(bin.end)
)
}),
start: bin.start,
tone,
value,
width: (x(bin.end) - x(bin.start) - 1.0).max(0.0),
x: x(bin.start),
y: frame.y(value),
}
})
.collect()
} else {
Vec::new()
};
let labels: Vec<String> = boundaries
.iter()
.map(|value| boundary.format(*value))
.collect();
let positions: Vec<f64> = boundaries.iter().map(|value| x(*value)).collect();
let ticks = category_ticks(
&labels,
CategoryTickOptions::new(frame.left, frame.right)
.bounds(0.0, frame.width)
.maximum_font_size(frame.axis_font_size)
.positions(&positions),
);
IntervalModel {
density_counts: (frequency == HistogramFrequency::Density).then(|| {
if finite {
bins.iter().map(|bin| bin.count).collect()
} else {
Vec::new()
}
}),
frame,
valid: finite,
marks,
category_ticks: ticks,
connectors: Vec::new(),
format_boundary: Some(boundary),
}
}
struct IntervalOptions<'a> {
model: IntervalModel,
value_label: String,
labels: ChartLabels,
format_value: Option<Callback<f64, String>>,
show_table: bool,
summary: Option<String>,
heading: Option<&'a String>,
attributes: &'a [Attribute],
}
#[derive(Clone, PartialEq)]
struct MarkView {
key: String,
tone: &'static str,
x: String,
y: String,
width: String,
height: String,
title: String,
label: String,
start: String,
end: String,
value: String,
count: Option<String>,
}
fn interval_plot(options: IntervalOptions<'_>) -> (Option<String>, Element) {
let IntervalOptions {
model,
value_label,
labels,
format_value,
show_table,
summary,
heading,
attributes,
} = options;
let format = |value: f64| format_with(format_value.as_ref(), value);
let boundary = |value: f64| {
model
.format_boundary
.map_or_else(|| format(value), |formatter| formatter.format(value))
};
let series = [ChartSeries::new(
"values",
value_label.clone(),
model.marks.iter().map(|mark| {
ChartDatum::new(mark.key.clone(), mark.value).with_x_label(mark.label.clone())
}),
)];
let factual = labels.summary(summarize(&series, format_value.as_ref()));
let summary = summary.or_else(|| {
Some(if model.valid {
factual
} else {
labels.invalid_data.clone()
})
});
if model.marks.is_empty() {
let message = if model.valid {
&labels.empty
} else {
&labels.invalid_data
};
return (summary, empty_status(message));
}
let counts = model.density_counts.clone();
let marks: Vec<MarkView> = model
.marks
.iter()
.enumerate()
.map(|(index, mark)| MarkView {
key: mark.key.clone(),
tone: mark.tone.class_name(),
x: js_number(mark.x),
y: js_number(mark.y),
width: js_number(mark.width),
height: js_number(mark.height),
title: format!("{}: {}", mark.label, format(mark.value)),
label: mark.label.clone(),
start: boundary(mark.start),
end: boundary(mark.end),
value: format(mark.value),
count: counts.as_ref().map(|counts| {
counts
.get(index)
.map_or_else(String::new, |count| js_number(*count))
}),
})
.collect();
let plot = plot_label(attributes, heading, &labels.chart_data);
let svg = interval_svg(&model, &marks);
let table = show_table.then(|| interval_table(&labels, &value_label, counts.is_some(), &marks));
let body = rsx! {
p { class: "ui-chart__axis-title", "{value_label}" }
div { class: "ui-chart__plot", role: "region", tabindex: "0", aria_label: "{plot}", {svg} }
if let Some(table) = table {
{table}
}
};
(summary, body)
}
fn interval_svg(model: &IntervalModel, marks: &[MarkView]) -> Element {
let frame = &model.frame;
let view_box = format!("0 0 {} {}", js_number(frame.width), js_number(frame.height));
let viewbox_width = js_number(frame.width);
let left = js_number(frame.left);
let right = js_number(frame.right);
let text_x = js_number(frame.left - 8.0);
let grid: Vec<(String, String, String)> = frame
.ticks
.iter()
.zip(&frame.tick_labels)
.map(|(tick, label)| (js_number(*tick), js_number(frame.y(*tick)), label.clone()))
.collect();
let axis_y = js_number(frame.height - 16.0);
let axis: Vec<(usize, &'static str, String, String)> = model
.category_ticks
.iter()
.map(|tick| {
(
tick.index,
CategoryTick::ANCHOR,
js_number(tick.position),
tick.label.clone(),
)
})
.collect();
let connectors: Vec<(String, String, String)> = model
.connectors
.iter()
.map(|connector| {
(
js_number(connector.x1),
js_number(connector.x2),
js_number(connector.y),
)
})
.collect();
rsx! {
svg { "aria-hidden": "true", "style": "--ui-chart-viewbox-width: {viewbox_width}", "viewBox": "{view_box}",
g { class: "ui-chart__grid",
for (key, y, text) in grid {
line { key: "{key}", "x1": "{left}", "x2": "{right}", "y1": "{y}", "y2": "{y}" }
text { "x": "{text_x}", "y": "{y}", "{text}" }
}
}
g { class: "ui-chart__axis-labels",
for (index, anchor, x, label) in axis {
text { key: "{index}", "text-anchor": anchor, "x": "{x}", "y": "{axis_y}", "{label}" }
}
}
for (x1, x2, y) in connectors {
line {
key: "{x1}",
class: "ui-waterfall-chart__connector",
"x1": "{x1}",
"x2": "{x2}",
"y1": "{y}",
"y2": "{y}",
}
}
g { class: "ui-bar-chart__marks",
for mark in marks.iter() {
rect {
key: "{mark.key}",
class: mark.tone,
"x": "{mark.x}",
"y": "{mark.y}",
"width": "{mark.width}",
"height": "{mark.height}",
title { "{mark.title}" }
}
}
}
}
}
}
fn interval_table(
labels: &ChartLabels,
value_label: &str,
density: bool,
marks: &[MarkView],
) -> Element {
rsx! {
details { class: "ui-chart__data",
summary { "{labels.view_data}" }
div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
table {
thead {
tr {
th { scope: "col", "{labels.category}" }
th { scope: "col", "{labels.start}" }
th { scope: "col", "{labels.end}" }
th { scope: "col", "{value_label}" }
if density {
th { scope: "col", "{labels.count}" }
}
}
}
tbody {
for mark in marks.iter() {
tr { key: "{mark.key}",
th { scope: "row", "{mark.label}" }
td { "{mark.start}" }
td { "{mark.end}" }
td { "{mark.value}" }
if let Some(count) = &mark.count {
td { "{count}" }
}
}
}
}
}
}
}
}
}
#[component]
pub fn WaterfallChart(props: WaterfallChartProps) -> Element {
let labels = props.labels.clone().unwrap_or_default();
let model = waterfall_geometry(&props.data, props.format_value.as_ref());
let (summary, body) = interval_plot(IntervalOptions {
model,
value_label: props
.value_label
.clone()
.unwrap_or_else(|| labels.value.clone()),
format_value: props.format_value,
show_table: props.show_table,
summary: props.summary.clone(),
heading: props.heading.as_ref(),
attributes: &props.attributes,
labels,
});
let class = compose([Some("ui-waterfall-chart"), props.class.as_deref()]);
render_frame(
super::super::frame::chart_frame!(props, class, summary),
body,
)
}
#[component]
pub fn Histogram(props: HistogramProps) -> Element {
let labels = props.labels.clone().unwrap_or_default();
let model = histogram_geometry(
&props.bins,
props.frequency,
props.tone,
props.format_boundary.as_ref(),
props.format_value.as_ref(),
);
let default_label = match props.frequency {
HistogramFrequency::Count => labels.count.clone(),
HistogramFrequency::Density => labels.density.clone(),
};
let (summary, body) = interval_plot(IntervalOptions {
model,
value_label: props.value_label.clone().unwrap_or(default_label),
format_value: props.format_value,
show_table: props.show_table,
summary: props.summary.clone(),
heading: props.heading.as_ref(),
attributes: &props.attributes,
labels,
});
let class = compose([Some("ui-histogram"), props.class.as_deref()]);
render_frame(
super::super::frame::chart_frame!(props, class, summary),
body,
)
}
#[cfg(test)]
mod tests {
use super::{
HistogramBin, HistogramFrequency, WaterfallChartDatum, histogram_geometry,
waterfall_geometry,
};
use crate::charts::model::{ChartDomain, ChartTone};
fn steps() -> Vec<WaterfallChartDatum> {
vec![
WaterfallChartDatum::total("open", "Opening", 120.0),
WaterfallChartDatum::delta("sales", "Sales", 45.0),
WaterfallChartDatum::delta("refunds", "Refunds", -18.0),
WaterfallChartDatum::total("close", "Closing", 147.0),
]
}
#[test]
fn waterfall_steps_carry_the_balance() {
let model = waterfall_geometry(&steps(), None);
assert!(model.valid);
let spans: Vec<(f64, f64)> = model
.marks
.iter()
.map(|mark| (mark.start, mark.end))
.collect();
assert_eq!(
spans,
vec![(0.0, 120.0), (120.0, 165.0), (165.0, 147.0), (0.0, 147.0)]
);
let tones: Vec<ChartTone> = model.marks.iter().map(|mark| mark.tone).collect();
assert_eq!(
tones,
vec![
ChartTone::Series1,
ChartTone::Series2,
ChartTone::Series5,
ChartTone::Series1
]
);
assert_eq!(model.connectors.len(), 3);
assert_eq!(model.frame.domain, ChartDomain::new(0.0, 200.0));
assert_eq!(model.frame.ticks, vec![0.0, 50.0, 100.0, 150.0, 200.0]);
assert_eq!(model.frame.tick_labels, ["0", "50", "100", "150", "200"]);
assert!((model.frame.left - 88.0).abs() < f64::EPSILON);
assert!((model.frame.top - 16.0).abs() < f64::EPSILON);
assert!((model.frame.right - 616.0).abs() < f64::EPSILON);
assert_eq!(
model
.category_ticks
.iter()
.map(|tick| tick.position)
.collect::<Vec<_>>(),
[154.0, 286.0, 418.0, 550.0]
);
assert!(model.format_boundary.is_none());
}
#[test]
fn negative_waterfalls_reach_below_zero() {
let model = waterfall_geometry(&[WaterfallChartDatum::delta("a", "Loss", -30.0)], None);
assert!(model.valid);
assert_eq!(model.frame.domain, ChartDomain::new(-30.0, 0.0));
assert_eq!(model.frame.ticks, vec![-30.0, -20.0, -10.0, 0.0]);
}
#[test]
fn invalid_waterfalls_fail_closed() {
let duplicate = [
WaterfallChartDatum::delta("a", "A", 1.0),
WaterfallChartDatum::delta("a", "B", 2.0),
];
let infinite = [WaterfallChartDatum::delta("a", "A", f64::INFINITY)];
let overflow = [
WaterfallChartDatum::delta("a", "A", f64::MAX),
WaterfallChartDatum::delta("b", "B", f64::MAX),
];
for data in [&duplicate[..], &infinite[..], &overflow[..]] {
let model = waterfall_geometry(data, None);
assert!(!model.valid && model.marks.is_empty());
}
let empty = waterfall_geometry(&[], None);
assert!(empty.valid && empty.marks.is_empty());
}
#[test]
fn histogram_bins_are_sorted_and_scaled() {
let model = histogram_geometry(
&[
HistogramBin::new(10.0, 20.0, 4.0),
HistogramBin::new(0.0, 10.0, 2.0),
],
HistogramFrequency::Count,
ChartTone::Series1,
None,
None,
);
assert!(model.valid);
assert_eq!(model.marks[0].label, "0–10");
assert_eq!(model.category_ticks.len(), 3);
assert!(model.density_counts.is_none());
}
#[test]
fn histogram_boundaries_are_unique_sorted_and_normalize_negative_zero() {
let model = histogram_geometry(
&[
HistogramBin::new(20.0, 30.0, 1.0),
HistogramBin::new(-0.0, 10.0, 2.0),
HistogramBin::new(10.0, 20.0, 3.0),
],
HistogramFrequency::Count,
ChartTone::Series1,
None,
None,
);
let labels: Vec<&str> = model
.category_ticks
.iter()
.map(|tick| tick.label.as_str())
.collect();
assert_eq!(labels, ["0", "10", "20", "30"]);
assert_eq!(
model
.marks
.iter()
.map(|mark| mark.label.as_str())
.collect::<Vec<_>>(),
["-0–10", "10–20", "20–30"]
);
}
#[test]
fn histogram_boundaries_share_the_value_tick_format() {
let bins = [
HistogramBin::new(0.0, 5_000.0, 3.0),
HistogramBin::new(5_000.0, 10_000.0, 7.0),
HistogramBin::new(10_000.0, 15_000.0, 2.0),
];
let model = histogram_geometry(
&bins,
HistogramFrequency::Count,
ChartTone::Series1,
None,
None,
);
let labels: Vec<&str> = model.marks.iter().map(|mark| mark.label.as_str()).collect();
let ticks: Vec<(&str, f64)> = model
.category_ticks
.iter()
.map(|tick| (tick.label.as_str(), tick.position))
.collect();
assert_eq!(labels, ["0–5K", "5K–10K", "10K–15K"]);
assert!((model.frame.right - 615.090_909_090_909_1).abs() < 1e-9);
assert_eq!(ticks.len(), 4);
assert!((ticks[1].1 - 263.696_969_696_969_7).abs() < 1e-9);
assert_eq!(ticks[3].0, "15K");
assert_eq!(model.frame.domain, ChartDomain::new(0.0, 8.0));
assert_eq!(
model.format_boundary.map(|format| format.format(2_500.0)),
Some("2.5K".to_string())
);
}
#[test]
fn density_allows_unequal_widths() {
let bins = [
HistogramBin::new(0.0, 5.0, 10.0),
HistogramBin::new(5.0, 20.0, 6.0),
];
let count = histogram_geometry(
&bins,
HistogramFrequency::Count,
ChartTone::Series1,
None,
None,
);
assert!(!count.valid && count.marks.is_empty());
let density = histogram_geometry(
&bins,
HistogramFrequency::Density,
ChartTone::Series1,
None,
None,
);
assert!(density.valid);
assert!((density.marks[0].value - 2.0).abs() < f64::EPSILON);
assert_eq!(density.density_counts, Some(vec![10.0, 6.0]));
}
#[test]
fn invalid_bins_fail_closed() {
let tone = ChartTone::Series1;
let count = HistogramFrequency::Count;
for bins in [
vec![HistogramBin::new(0.0, 0.0, 1.0)],
vec![HistogramBin::new(0.0, 1.0, -1.0)],
vec![HistogramBin::new(0.0, f64::NAN, 1.0)],
vec![
HistogramBin::new(0.0, 2.0, 1.0),
HistogramBin::new(1.0, 3.0, 1.0),
],
vec![HistogramBin::new(-f64::MAX, f64::MAX, 1.0)],
] {
assert!(!histogram_geometry(&bins, count, tone, None, None).valid);
}
let empty = histogram_geometry(&[], count, tone, None, None);
assert!(empty.valid && empty.marks.is_empty());
assert_eq!(empty.category_ticks.len(), 0);
}
}