Chartjs-Fix number distributions after scaling the range

0👍

You need to normalize your entries to sum up to the same number. You can divide each entry by the sum of entire set and multiply by the desired sum:

function normalizeDistribution(entries, max) {
    const sum = entries.reduce((sum, entry) => sum + entry);
    return entries.map(n => n / sum * max);
}

And here’s how you use it:

const list = [[1, 8, 3, 9], [10, 2, 7, 6]];
const max = 10;
const normalizedList = list.map(entries => normalizeDistribution(entries, max));

/*

result:
[
    [0.47619047619047616, 3.8095238095238093, 1.4285714285714284, 4.285714285714286],
    [4, 0.8, 2.8000000000000003, 2.4]
]

*/

Now, you can pass normalizedList to your chart and it will generate full-width bars.

Leave a comment