This demo shows how we can pre-process the raw point data to display a histogram of point distribution.
Code
We are going to use custom code to turn the following raw point data into a categorized data that can be used in an XY chart.
[3.5, 3, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3, 3, 4, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3, 3.8, 3.2, 3.7, 3.3, 3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2, 3, 2.2, 2.9, 2.9, 3.1, 3, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3, 2.8, 3, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3, 3.4, 3.1, 2.3, 3, 2.5, 2.6, 3, 2.6, 2.3, 2.7, 3, 2.9, 2.9, 2.5, 2.8, 3.3, 2.7, 3, 2.9, 3, 3, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3, 2.5, 2.8, 3.2, 3, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3, 2.8, 3, 2.8, 3.8, 2.8, 2.8, 2.6, 3, 3.4, 3.1, 3, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3, 2.5, 3, 3.4, 3]
The following code will:
- Measure the scope of values.
- Divide into X number of range of values - categories.
- Count the number of points that fall into each value range (category).
- Build categorized data for use in a chart.
let maxCols = 10;
function getHistogramData(source) {
// Init
let data = [];
let min = Math.min.apply(null, source);
let max = Math.max.apply(null, source);
let range = max - min;
let step = range / maxCols;
// Create items
for(let i = 0; i < maxCols; i++) {
let from = min + i * step;
let to = min + (i + 1) * step;
data.push({
from: from,
to: to,
count: 0
});
}
// Calculate range of the values
for(let i = 0; i < source.length; i++) {
let value = source[i];
let item = data.find(function(el) {
return (value >= el.from) && (value <= el.to);
});
item.count++;
}
return data;
}
let data = getHistogramData(sourceData);
var maxCols = 10;
function getHistogramData(source) {
// Init
var data = [];
var min = Math.min.apply(null, source);
var max = Math.max.apply(null, source);
var range = max - min;
var step = range / maxCols;
// Create items
for(var i = 0; i < maxCols; i++) {
var from = min + i * step;
var to = min + (i + 1) * step;
data.push({
from: from,
to: to,
count: 0
});
}
// Calculate range of the values
for(var i = 0; i < source.length; i++) {
var value = source[i];
var item = data.find(function(el) {
return (value >= el.from) && (value <= el.to);
});
item.count++;
}
return data;
}
var data = getHistogramData(sourceData);
Here's how data looks like after processing:
[
{ from: 2, to: 2.24, count: 4 },
{ from: 2.24, to: 2.48, count: 7 },
{ from: 2.48, to: 2.72, count: 22 },
{ from: 2.72, to: 2.96, count: 24 },
{ from: 2.96, to: 3.2, count: 50 },
{ from: 3.2, to: 3.44, count: 18 },
{ from: 3.44, to: 3.68, count: 10 },
{ from: 3.68, to: 3.92, count: 11 },
{ from: 3.92, to: 4.16, count: 2 },
{ from: 4.16, to: 4.4, count: 2 }
]
Demo
See the Pen #78332 by amCharts team (@amcharts) on CodePen.