Skip to content

Instantly share code, notes, and snippets.

@PBrockmann
Last active March 5, 2024 12:15
Show Gist options
  • Save PBrockmann/5e7b2ce5edf2e326c88800d4303da0dd to your computer and use it in GitHub Desktop.
Save PBrockmann/5e7b2ce5edf2e326c88800d4303da0dd to your computer and use it in GitHub Desktop.
Interactive D3.js heatmap
.heatmap {
font-size: 8px;
font-family: monospace;
}
rect.bordered {
stroke: #E6E6E6;
stroke-width:2px;
}
text.mono {
font-size: 8px;
font-family: monospace;
fill: #000;
}
text.legendElement {
font-size: 10px;
}
text.hover {
font-weight: bold;
fill: #66F;
font-background: #000;
}
.heatmap_tooltip {
text-align: center;
font-family: monospace;
font-size: 14pt;
color: #000;
position: relative;
background: rgba(255, 255, 255, 0.8);
border: 4px solid #66F;
padding: 5px;
border-radius: 8px ;
-webkit-border-top-left-radius: 8px;
-webkit-border-top-right-radius: 8px;
-webkit-border-bottom-right-radius: 8px;
-webkit-border-bottom-left-radius: 8px;
-khtml-border-top-left-radius: 8px;
-khtml-border-top-right-radius: 8px;
-khtml-border-bottom-right-radius: 8px;
-khtml-border-bottom-left-radius: 8px;
-moz-border-radius-topleft: 8px;
-moz-border-radius-topright: 8px;
-moz-border-radius-bottomright: 8px;
-moz-border-radius-bottomleft: 8px;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
border-bottom-right-radius: 8px;
border-bottom-left-radius: 8px;
width: 100px;
z-index:10000;
-webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.8);
-moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.8);
box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.8);
}
.heatmap_tooltip:after, .heatmap_tooltip:before {
top: 100%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.heatmap_tooltip:after {
border-color: rgba(236, 240, 241, 0);
border-top-color: #FFFFF;
border-width: 10px;
left: 50%;
margin-left: -10px;
}
.heatmap_tooltip:before {
border-color: rgba(44, 62, 80, 0);
border-top-color: #66F;
border-width: 16px;
left: 50%;
margin-left: -16px;
}
var classesNumber = 10,
cellSize = 24;
//#########################################################
function heatmap_display(url, heatmapId, paletteName) {
//##########################################################################
// [email protected]
//##########################################################################
//==================================================
// References
// http://bl.ocks.org/Soylent/bbff6cc507dca2f48792
// http://bost.ocks.org/mike/selection/
// http://bost.ocks.org/mike/join/
// http://stackoverflow.com/questions/9481497/understanding-how-d3-js-binds-data-to-nodes
// http://bost.ocks.org/mike/miserables/
// http://bl.ocks.org/ianyfchang/8119685
//==================================================
var tooltip = d3.select(heatmapId)
.append("div")
.style("position", "absolute")
.style("visibility", "hidden");
//==================================================
// http://bl.ocks.org/mbostock/3680958
function zoom() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
// define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom);
//==================================================
var viewerWidth = $(document).width();
var viewerHeight = $(document).height();
var viewerPosTop = 200;
var viewerPosLeft = 100;
var legendElementWidth = cellSize * 2;
// http://bl.ocks.org/mbostock/5577023
var colors = colorbrewer[paletteName][classesNumber];
// http://bl.ocks.org/mbostock/3680999
var svg;
//==================================================
d3.json(url, function(error, data) {
//console.log(data);
var arr = data.data;
var row_number = arr.length;
var col_number = arr[0].length;
//console.log(col_number, row_number);
var colorScale = d3.scale.quantize()
.domain([0.0, 1.0])
.range(colors);
svg = d3.select(heatmapId).append("svg")
.attr("width", viewerWidth)
.attr("height", viewerHeight)
.call(zoomListener)
.append("g")
.attr("transform", "translate(" + viewerPosLeft + "," + viewerPosTop + ")");
svg.append('defs')
.append('pattern')
.attr('id', 'diagonalHatch')
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 4)
.attr('height', 4)
.append('path')
.attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
.attr('stroke', '#000000')
.attr('stroke-width', 1);
var rowSortOrder = false;
var colSortOrder = false;
var rowLabels = svg.append("g")
.attr("class", "rowLabels")
.selectAll(".rowLabel")
.data(data.index)
.enter().append("text")
.text(function(d) {
return d.count > 1 ? d.join("/") : d;
})
.attr("x", 0)
.attr("y", function(d, i) {
return (i * cellSize);
})
.style("text-anchor", "end")
.attr("transform", function(d, i) {
return "translate(-3," + cellSize / 1.5 + ")";
})
.attr("class", "rowLabel mono")
.attr("id", function(d, i) {
return "rowLabel_" + i;
})
.on('mouseover', function(d, i) {
d3.select('#rowLabel_' + i).classed("hover", true);
})
.on('mouseout', function(d, i) {
d3.select('#rowLabel_' + i).classed("hover", false);
})
.on("click", function(d, i) {
rowSortOrder = !rowSortOrder;
sortByValues("r", i, rowSortOrder);
d3.select("#order").property("selectedIndex", 0);
//$("#order").jqxComboBox({selectedIndex: 0});
});
var colLabels = svg.append("g")
.attr("class", "colLabels")
.selectAll(".colLabel")
.data(data.columns)
.enter().append("text")
.text(function(d) {
d.shift();
return d.count > 1 ? d.reverse().join("/") : d.reverse();
})
.attr("x", 0)
.attr("y", function(d, i) {
return (i * cellSize);
})
.style("text-anchor", "left")
.attr("transform", function(d, i) {
return "translate(" + cellSize / 2 + ", -3) rotate(-90) rotate(45, 0, " + (i * cellSize) + ")";
})
.attr("class", "colLabel mono")
.attr("id", function(d, i) {
return "colLabel_" + i;
})
.on('mouseover', function(d, i) {
d3.select('#colLabel_' + i).classed("hover", true);
})
.on('mouseout', function(d, i) {
d3.select('#colLabel_' + i).classed("hover", false);
})
.on("click", function(d, i) {
colSortOrder = !colSortOrder;
sortByValues("c", i, colSortOrder);
d3.select("#order").property("selectedIndex", 0);
});
var row = svg.selectAll(".row")
.data(data.data)
.enter().append("g")
.attr("id", function(d) {
return d.idx;
})
.attr("class", "row");
var j = 0;
var heatMap = row.selectAll(".cell")
.data(function(d) {
j++;
return d;
})
.enter().append("svg:rect")
.attr("x", function(d, i) {
return i * cellSize;
})
.attr("y", function(d, i, j) {
return j * cellSize;
})
.attr("rx", 4)
.attr("ry", 4)
.attr("class", function(d, i, j) {
return "cell bordered cr" + j + " cc" + i;
})
.attr("row", function(d, i, j) {
return j;
})
.attr("col", function(d, i, j) {
return i;
})
.attr("width", cellSize)
.attr("height", cellSize)
.style("fill", function(d) {
if (d != null) return colorScale(d);
else return "url(#diagonalHatch)";
})
.on('mouseover', function(d, i, j) {
d3.select('#colLabel_' + i).classed("hover", true);
d3.select('#rowLabel_' + j).classed("hover", true);
if (d != null) {
tooltip.html('<div class="heatmap_tooltip">' + d.toFixed(3) + '</div>');
tooltip.style("visibility", "visible");
} else
tooltip.style("visibility", "hidden");
})
.on('mouseout', function(d, i, j) {
d3.select('#colLabel_' + i).classed("hover", false);
d3.select('#rowLabel_' + j).classed("hover", false);
tooltip.style("visibility", "hidden");
})
.on("mousemove", function(d, i) {
tooltip.style("top", (d3.event.pageY - 55) + "px").style("left", (d3.event.pageX - 60) + "px");
})
.on('click', function() {
//console.log(d3.select(this));
});
var legend = svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(0,-300)")
.selectAll(".legendElement")
.data([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
.enter().append("g")
.attr("class", "legendElement");
legend.append("svg:rect")
.attr("x", function(d, i) {
return legendElementWidth * i;
})
.attr("y", viewerPosTop)
.attr("class", "cellLegend bordered")
.attr("width", legendElementWidth)
.attr("height", cellSize / 2)
.style("fill", function(d, i) {
return colors[i];
});
legend.append("text")
.attr("class", "mono legendElement")
.text(function(d) {
return "≥" + Math.round(d * 100) / 100;
})
.attr("x", function(d, i) {
return legendElementWidth * i;
})
.attr("y", viewerPosTop + cellSize);
//==================================================
// Change ordering of cells
function sortByValues(rORc, i, sortOrder) {
var t = svg.transition().duration(1000);
var values = [];
var sorted;
d3.selectAll(".c" + rORc + i)
.filter(function(d) {
if (d != null) values.push(d);
else values.push(-999); // to handle NaN
});
//console.log(values);
if (rORc == "r") { // sort on cols
sorted = d3.range(col_number).sort(function(a, b) {
if (sortOrder) {
return values[b] - values[a];
} else {
return values[a] - values[b];
}
});
t.selectAll(".cell")
.attr("x", function(d) {
var col = parseInt(d3.select(this).attr("col"));
return sorted.indexOf(col) * cellSize;
});
t.selectAll(".colLabel")
.attr("y", function(d, i) {
return sorted.indexOf(i) * cellSize;
})
.attr("transform", function(d, i) {
return "translate(" + cellSize / 2 + ", -3) rotate(-90) rotate(45, 0, " + (sorted.indexOf(i) * cellSize) + ")";
});
} else { // sort on rows
sorted = d3.range(row_number).sort(function(a, b) {
if (sortOrder) {
return values[b] - values[a];
} else {
return values[a] - values[b];
}
});
t.selectAll(".cell")
.attr("y", function(d) {
var row = parseInt(d3.select(this).attr("row"));
return sorted.indexOf(row) * cellSize;
});
t.selectAll(".rowLabel")
.attr("y", function(d, i) {
return sorted.indexOf(i) * cellSize;
})
.attr("transform", function(d, i) {
return "translate(-3," + cellSize / 1.5 + ")";
});
}
}
//==================================================
d3.select("#order").on("change", function() {
var newOrder = d3.select("#order").property("value");
changeOrder(newOrder, heatmapId);
});
//==================================================
d3.select("#palette")
.on("keyup", function() {
var newPalette = d3.select("#palette").property("value");
if (newPalette != null) // when interfaced with jQwidget, the ComboBox handles keyup event but value is then not available ?
changePalette(newPalette, heatmapId);
})
.on("change", function() {
var newPalette = d3.select("#palette").property("value");
changePalette(newPalette, heatmapId);
});
});
//==================================================
}
//#########################################################
function changeOrder(newOrder, heatmapId) {
var svg = d3.select(heatmapId);
var t = svg.transition().duration(1000);
if (newOrder == "sortinit_col") { // initial sort on cols (alphabetically if produced like this)
t.selectAll(".cell")
.attr("x", function(d) {
var col = parseInt(d3.select(this).attr("col"));
return col * cellSize;
});
t.selectAll(".colLabel")
.attr("y", function(d, i) {
return i * cellSize;
})
.attr("transform", function(d, i) {
return "translate(" + cellSize / 2 + ", -3) rotate(-90) rotate(45, 0, " + (i * cellSize) + ")";
});
} else if (newOrder == "sortinit_row") { // initial sort on rows (alphabetically if produced like this)
t.selectAll(".cell")
.attr("y", function(d) {
var row = parseInt(d3.select(this).attr("row"));
return row * cellSize;
});
t.selectAll(".rowLabel")
.attr("y", function(d, i) {
return i * cellSize;
})
.attr("transform", function(d, i) {
return "translate(-3," + cellSize / 1.5 + ")";
});
} else if (newOrder == "sortinit_col_row") { // initial sort on rows and cols (alphabetically if produced like this)
t.selectAll(".cell")
.attr("x", function(d) {
var col = parseInt(d3.select(this).attr("col"));
return col * cellSize;
})
.attr("y", function(d) {
var row = parseInt(d3.select(this).attr("row"));
return row * cellSize;
});
t.selectAll(".colLabel")
.attr("y", function(d, i) {
return i * cellSize;
})
.attr("transform", function(d, i) {
return "translate(" + cellSize / 2 + ", -3) rotate(-90) rotate(45, 0, " + (i * cellSize) + ")";
});
t.selectAll(".rowLabel")
.attr("y", function(d, i) {
return i * cellSize;
})
.attr("transform", function(d, i) {
return "translate(-3," + cellSize / 1.5 + ")";
});
}
}
//#########################################################
function changePalette(paletteName, heatmapId) {
var colors = colorbrewer[paletteName][classesNumber];
var colorScale = d3.scale.quantize()
.domain([0.0, 1.0])
.range(colors);
var svg = d3.select(heatmapId);
var t = svg.transition().duration(500);
t.selectAll(".cell")
.style("fill", function(d) {
if (d != null) return colorScale(d);
else return "url(#diagonalHatch)";
})
t.selectAll(".cellLegend")
.style("fill", function(d, i) {
return colors[i];
});
}
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<!--
##########################################################################
[email protected]
##########################################################################
-->
<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://d3js.org/colorbrewer.v1.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="heatmap.js"></script>
<link rel="stylesheet" href="heatmap.css" />
<head>
<script>
$(document).ready(function() {
heatmap_display("metrics_ocmip5.json", "#heatmap", "Spectral");
});
</script>
</head>
<body>
Order:
<select id="order">
<option value="null" selected> ----- </option>
<option value="sortinit_col_row">Initial order on columns and rows</option>
<option value="sortinit_row">Initial order on rows</option>
<option value="sortinit_col">Initial order on columns</option>
</select>
Palette:
<select id="palette">
<option value="RdYlGn">RdYlGn</option>
<option value="Spectral" selected>Spectral</option>
<option value="RdYlBu">RdYlBu</option>
<option value="RdGy">RdGy</option>
<option value="RdBu">RdBu</option>
<option value="PiYG">PiYG</option>
<option value="PRGn">PRGn</option>
<option value="BrBG">BrBG</option>
<option value="PuOr">PuOr</option>
</select>
<div id="heatmap"></div>
</body>
</html>
MIT License
Copyright (c) 2019 Patrick Brockmann / LSCE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{"columns":[["R","BLT"],["R","BLTm"],["R","BLTmax"],["R","BLTmin"],["R","BLTmmin"],["R","BLTp"],["R","BLTpmax"],["R","BetaD"],["R","CO3"],["R","DIC"],["R","MLDd"],["R","MLDdmax"],["R","MLDdmin"],["R","MLDdt"],["R","MLDdtmax"],["R","MLDdtmin"],["R","MLDt"],["R","MLDtmax"],["R","MLDtmin"],["R","NO3"],["R","O2"],["R","OmegaA"],["R","OmegaC"],["R","PCO2surf"],["R","PO4"],["R","SALT"],["R","SI"],["R","TALK"],["R","TEMP"],["R","TTD"],["R","TTDmax"],["R","TTDmin"],["R","fgCO2"],["R","pCO2"],["R","pH"]],"index":[["BCCR","BCM-C"],["IFM","UVIC2-8"],["IPSL","IPSL-CM4"],["MPI-M","COSMOS"],["UBERN","CCSM3"],["UBERN","CSM1-4"]],"data":[[0.1178,0.4834,0.1647,0.1633,0.3355,0.1353,0.0556,0.9388,0.9354,0.8548,0.7037,0.6092,0.3835,0.7285,0.6405,0.424,0.6935,0.5766,0.2275,0.8309,0.972,0.9439,0.9366,0.5326,0.827,0.84265,null,0.6789,0.9873,0.3443,0.2011,-0.0111,0.5932,0.55785,0.551],[0.0372,-0.09,0.5015,0.5663,0.5126,-0.0274,0.4304,0.9518,0.9499,0.9216,-0.0278,0.6516,0.3019,-0.0936,0.6597,0.2323,-0.0833,0.4921,0.122,0.9275,0.96095,0.955,0.9501,0.42975,0.8963,0.85245,null,0.8149,0.9661,0.0217,0.5005,0.0184,0.3244,0.44105,0.2685],[0.378,0.5514,0.378,0.3929,0.3271,0.3816,0.3647,0.9303,0.9372,0.8356,0.5314,0.4069,0.4288,0.5496,0.4156,0.427,0.5299,0.3454,0.4511,0.88235,0.9705,0.9468,0.9405,null,0.8588,0.7931,0.57945,0.6422,0.98325,0.5374,0.4769,0.058,0.67085,0.6671,0.2607],[0.4988,0.4149,0.5952,0.0628,-0.1015,0.497,0.58,0.9531,0.9572,0.8494,0.6262,0.3854,0.6904,0.5711,0.346,0.5132,0.583,0.3917,0.5305,0.7074,0.9763,0.9632,0.9582,0.55465,0.7606,0.8894,null,0.7035,0.98965,0.639,0.7028,0.0336,0.47125,null,0.262],[0.3922,0.3998,0.5056,0.3661,0.152,0.4573,0.4885,0.931,0.9348,0.778,0.6927,0.4853,0.5339,0.6709,0.4897,0.4935,0.7281,0.5822,0.367,0.88845,0.97155,0.9445,0.938,0.69285,0.83455,0.69815,0.6801,0.5364,0.9852,0.4375,0.5223,0.2292,0.58835,0.6749,0.2428],[0.3938,0.4745,0.5258,0.3881,0.2779,0.3858,0.5034,0.933,0.9434,0.8609,0.6526,0.519,0.4422,0.642,0.5325,0.3576,0.6381,0.5626,0.2691,null,0.9827,0.9488,0.943,0.6232,0.72975,0.75015,null,0.6966,0.98575,0.4605,0.5593,0.0065,0.6264,null,0.3202]]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment