Skip to content

Data ​

Numbers ​

The usual input is an array of numbers. Numeric strings such as '4.2' are read as numbers. Anything else, such as null, undefined, NaN, Infinity or 'abc', is left out and counted in dropped:

js
{
  data: [1.5, 2, '3.25', null, NaN];
} // 3 values binned, 2 dropped

Objects ​

When data holds objects, the value is read from the key in parsing.key, y by default. A dotted path reads a nested key:

js
{data: [{y: 4}, {y: 7}]}
{data: [{height: 170}, {height: 182}], parsing: {key: 'height'}}
{data: [{person: {height: 170}}], parsing: {key: 'person.height'}}

A two-element array [x, y] gives its second element, so the [x, y] pairs of a line chart can be binned as they are.

Values of another dataset ​

source bins the values of another dataset, read from its raw data. The histogram's own data is ignored:

js
datasets: [
  {type: 'line', id: 'readings', label: 'Readings', data: readings},
  {type: 'histogram', data: [], source: 'readings', binWidth: 0.5}
];

Pre-binned data ​

When the counting happened elsewhere, for example in a database, pass the bins as {x0, x1, y} records and set parsing: false. x0 and x1 are the bin's edges, y its count:

js
{
  parsing: false,
  data: [
    {x0: 0, x1: 10, y: 123},
    {x0: 10, x1: 20, y: 420},
    {x0: 20, x1: 40, y: 650}
  ]
}

The records may come in any order. A gap between two records becomes an empty bin. A record that overlaps the one before it is left out with the warning invalid-prebinned, and so is a record whose edges are not finite numbers with x0 < x1, or whose y is negative. stat and cumulative apply as usual; the binning options do not.

Updates ​

Change the data or the options and call chart.update(), as with any Chart.js chart. The values are binned again on every update. Pushing values onto the array, replacing the array, and changing any option all work:

js
chart.data.datasets[0].data.push(42);
chart.update();

chart.data.datasets[0].data = newValues;
chart.data.datasets[0].bins = 'fd';
chart.update();

Released under the MIT License.