Heat map

From JSXGraph Wiki
Revision as of 20:07, 6 March 2012 by A WASSERMANN (talk | contribs)

The underlying JavaScript code

// Given is a 2D data array of size (len x len) containing integer values 
// from 0 to (bins-1). 
var len = 20;
var bins = 5;
// Here, we just create random values.
var xyArr = [];
var i, j;
for (i=0; i<len; i++) {	
	xyArr[i] = [];
	for (j=0; j<len; j++) {	
		xyArr[i][j] = Math.round(Math.random()*(bins-1));
	}
}

// Now, xyArr is a 2D array containing the random integer values and we can start
// creating the heat map.
var brd = JXG.JSXGraph.initBoard('jxgbox', {boundingbox:[-0.5,len+0.5, len+0.5, 0.5], 
	keepaspectratio:false, showNavigation:true});

// spot() creates a quadratic single filled curve centered around (x,y). 
var spot = function(board, y, x, v, maxVal) {
	var c = JXG.hsv2rgb(270.0-v*270.0/maxVal, 0.8, 1.0); 
	return board.create('curve', 
		[[x-0.5, x+0.5, x+0.5, x-0.5, x-0.5],
		 [y-0.5, y-0.5, y+0.5, y+0.5, y-0.5]],
		{strokeWidth:0, fillColor:c, highlightFillColor:c, highlightFillOpacity:0.8});
	};

var createHeatMap = function(board, arr2D, xlen, ylen, bins) {
            var i, j, heat = [];
            
            board.suspendUpdate();
            for (i=0; i<ylen; i++) {	
	        heat[i] = [];
	        for (j=0; j<xlen; j++) {	
		    heat[i][j] = spot(board, i, j, xyArr[i][j], bins-1);
	        }
            }
            board.unsuspendUpdate();
            return heat;
        };

createHeatMap(brd, xyArr, len, len, bins);