JavaScript Histogram of Gaussian Distribution.
Example showcasing LightningChart Histogram visualization using Bar Chart.
Bar Chart can be used as a histogram by calculating the bins manually using the following function:
const calculateHistogramBins = (data, numberOfBins) => {
const minValue = Math.min(...data)
const maxValue = Math.max(...data)
const binSize = (maxValue - minValue) / numberOfBins
// Calculate bin intervals
const bins = []
for (let i = 0; i < numberOfBins; i++) {
const binStart = minValue + i * binSize
const binEnd = minValue + (i + 1) * binSize
bins.push({
binStart: parseFloat(binStart.toFixed(2)),
binEnd: parseFloat(binEnd.toFixed(2)),
values: Array(),
})
}
bins[numberOfBins - 1].binEnd = maxValue
// Map data to bins
data.forEach((value) => {
const binIndex = Math.floor((value - minValue) / binSize)
if (binIndex >= 0 && binIndex < numberOfBins) {
bins[binIndex].values.push(value)
}
})
// Create input data for bar chart
const barChartData = []
bins.forEach((interval) => {
barChartData.push({
category: `${(interval.binStart + (interval.binStart === minValue ? 0 : 0.01)).toFixed(2)}—${
interval.binEnd < 0 ? `(${interval.binEnd.toFixed(2)})` : interval.binEnd.toFixed(2)
}`,
value: interval.values.length,
})
})
return barChartData
}
In this example, a normally distributed dataset is generated by the Box–Muller transform method:
const generateGaussianRandom = (length) => {
const samples = []
for (let i = 0; i < length; i++) {
let u = 0,
v = 0,
s = 0
while (s === 0 || s >= 1) {
u = Math.random() * 2 - 1
v = Math.random() * 2 - 1
s = u * u + v * v
}
const temp = Math.sqrt((-2 * Math.log(s)) / s)
const sample = u * temp
samples.push(sample)
}
return samples
}
In order to preserve the bell curve shape, automatic sorting has to be turned off by barChart.setSorting(BarChartSorting.Disabled)
The number of histogram bins can be changed dynamically by the user using the HTML number input. The chart updates automatically from these interactions.