Skip to main content

compute_bins

Function compute_bins 

Source
pub fn compute_bins(data: &[f64], num_bins: usize) -> (Vec<f64>, Vec<f64>)
Expand description

Computes equal-width bin edges and counts for a histogram.

Given a slice of data values and a desired number of bins, this function determines the bin edges and counts the number of data points that fall into each bin. Non-finite values (NaN, +Inf, -Inf) are silently ignored.

§Bin placement

Bins are equal-width and span the range [min, max] of the finite values, where min and max are the smallest and largest finite values in data. The i-th bin covers the half-open interval [edge[i], edge[i+1]), except for the last bin which is closed on both sides [edge[n-1], edge[n]] to include the maximum value.

§Single-value case

When all finite values are identical (i.e. max == min), the range is expanded to [min - 0.5, max + 0.5] so that the single value falls within the bin and the histogram has a visible width.

§Returns

A tuple (edges, counts) where:

  • edges is a Vec<f64> of length num_bins + 1 containing the sorted bin edges.
  • counts is a Vec<f64> of length num_bins containing the number of data points in each bin.

If data contains no finite values or num_bins is zero, both vectors are returned empty.

§Examples

use plotkit_core::charts::histogram::compute_bins;

let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let (edges, counts) = compute_bins(&data, 5);

assert_eq!(edges.len(), 6);    // 5 bins + 1
assert_eq!(counts.len(), 5);   // one count per bin

// Every value lands in exactly one bin.
let total: f64 = counts.iter().sum();
assert_eq!(total, 5.0);