George Ortiz George Ortiz - 6 months ago 74
Javascript Question

Add third color level to Javascript/JQuery HTML Table Heatmap

I'm using a HTML table heatmap JQuery script by:

http://www.designchemical.com/blog/index.php/jquery/jquery-tutorial-create-a-flexible-data-heat-map/

I've been able to modify it and get it cleaned up and working with our data sets. However, the current script only allows for two colors and does not calculate the medium with a standard deviation to include a third color such as yellow.

Here is the current script below:

<script type="text/JavaScript">
$(document).ready(function () {
// Function to get the Max value in Array
Array.max = function (array) {
return Math.max.apply(Math, array);
};

// get all values
var counts = $('.heatmap tbody td').not('.first_row').map(function () {
return parseInt($(this).text().replace(/,/g, "").replace(/\(|\)/g, ""));
}).get();

// return max value
var max = Array.max(counts);

// red color for lowest data
xr = 251;
xg = 121;
xb = 105;

// green color for highest data
yr = 138;
yg = 251;
yb = 107;
n = 100;

// add classes to cells based on nearest 10 value
$('.heatmap tbody td').not('.first_row').each(function () {
var val = parseInt($(this).text().replace(/,/g, "").replace(/\(|\)/g, ""));
var pos = parseInt((Math.round((val / max) * 100)).toFixed(0));
red = parseInt((xr + ((pos * (yr - xr)) / (n - 1))).toFixed(0));
green = parseInt((xg + ((pos * (yg - xg)) / (n - 1))).toFixed(0));
blue = parseInt((xb + ((pos * (yb - xb)) / (n - 1))).toFixed(0));
clr = 'rgb(' + red + ',' + green + ',' + blue + ')';
$(this).css({
backgroundColor: clr
});
});
});
</script>


The heatmap currently goes from red to green and I want to add a calculation that adds yellow for the medium range. I've created a jsFiddle here: http://jsfiddle.net/7z8D4/ with the script and heatmap table structure I'm using.

For Example, if I have the following data sets, it should be colored such as:

1 red
2 red
3 pink
4 pink
5 yellow
6 yellow
7 lime green
8 lime green
9 green
10 green


I really appreciate any insights on this. :)

Answer

red (at 0%) to yellow (at 50%) to green (at 100%)

var pos = val / (max * 1.0);

red =  Math.round(pos < 0.5 ? 255 : ((1 - pos) * 2) * 255);
green = Math.round(pos < 0.5 ? (pos * 2) * 255 : 255);
blue = 0;
Comments