Search code examples
javascriptgraphicshistogramcalculated-columnshistogram2d

Calculate histogram graphic columns height


I cannot figure out the easiest formula to calculate the height of column in histogram graphic.

For example, I have an array of data

var data = [82, 61, 88, 245, 201, 619, 735, 1099, 1088, 1477, 1531, 1717, 1263, 1674, 1254, 1134, 718, 887, 748, 569, 485, 565, 286, 266, 298, 203, 171, 235, 128, 127, 109, 128, 76, 73, 73, 85, 44, 33, 47, 29, 38, 47, 35, 31, 16, 17, 11, 20, 20, 276]

This is the list of numbers (each number in array represents the count of properties closer to edges of the range from 0 to 3000). I need max column height to be 30px. What kind of calculations should I make?

example of result

I imagine that my pseudocode should look as follows:

var maxPropertiesNumber = Math.max.apply(null, data);
var html = list.map(column => {
   var style = {
     width: 10px,
     backgroundColor: 'grey',
     height: ...
   };
   return <div style={style}></div>
})

Solution

    1. Find the maximum value in the array.
    2. Calculate: 30px / (maximum value) = pixels-per-unit
    3. Loop through values and perform calculation: round(value * pixel-per-unit)