Skip to content

Instantly share code, notes, and snippets.

@tommaybe
Last active November 20, 2020 04:12
Show Gist options
  • Save tommaybe/5558084 to your computer and use it in GitHub Desktop.
Save tommaybe/5558084 to your computer and use it in GitHub Desktop.
Day / Hour Heatmap

Inspired by Trulia Trends - but with code and using SVG.

Example data shows concurrent user sessions over time, taken from a development environment.

MIT Licensed, see LICENSE.MD.

day hour value
1 1 16
1 2 20
1 3 0
1 4 0
1 5 0
1 6 2
1 7 0
1 8 9
1 9 25
1 10 49
1 11 57
1 12 61
1 13 37
1 14 66
1 15 70
1 16 55
1 17 51
1 18 55
1 19 17
1 20 20
1 21 9
1 22 4
1 23 0
1 24 12
2 1 6
2 2 2
2 3 0
2 4 0
2 5 0
2 6 2
2 7 4
2 8 11
2 9 28
2 10 49
2 11 51
2 12 47
2 13 38
2 14 65
2 15 60
2 16 50
2 17 65
2 18 50
2 19 22
2 20 11
2 21 12
2 22 9
2 23 0
2 24 13
3 1 5
3 2 8
3 3 8
3 4 0
3 5 0
3 6 2
3 7 5
3 8 12
3 9 34
3 10 43
3 11 54
3 12 44
3 13 40
3 14 48
3 15 54
3 16 59
3 17 60
3 18 51
3 19 21
3 20 16
3 21 9
3 22 5
3 23 4
3 24 7
4 1 0
4 2 0
4 3 0
4 4 0
4 5 0
4 6 2
4 7 4
4 8 13
4 9 26
4 10 58
4 11 61
4 12 59
4 13 53
4 14 54
4 15 64
4 16 55
4 17 52
4 18 53
4 19 18
4 20 3
4 21 9
4 22 12
4 23 2
4 24 8
5 1 2
5 2 0
5 3 8
5 4 2
5 5 0
5 6 2
5 7 4
5 8 14
5 9 31
5 10 48
5 11 46
5 12 50
5 13 66
5 14 54
5 15 56
5 16 67
5 17 54
5 18 23
5 19 14
5 20 6
5 21 8
5 22 7
5 23 0
5 24 8
6 1 2
6 2 0
6 3 2
6 4 0
6 5 0
6 6 0
6 7 4
6 8 8
6 9 8
6 10 6
6 11 14
6 12 12
6 13 9
6 14 14
6 15 0
6 16 4
6 17 7
6 18 6
6 19 0
6 20 0
6 21 0
6 22 0
6 23 0
6 24 0
7 1 7
7 2 6
7 3 0
7 4 0
7 5 0
7 6 0
7 7 0
7 8 0
7 9 0
7 10 0
7 11 2
7 12 2
7 13 5
7 14 6
7 15 0
7 16 4
7 17 0
7 18 2
7 19 10
7 20 7
7 21 0
7 22 19
7 23 9
7 24 4
day hour value
1 1 88
1 2 20
1 3 44
1 4 0
1 5 33
1 6 2
1 7 0
1 8 9
1 9 25
1 10 1
1 11 57
1 12 61
1 13 22
1 14 25
1 15 7
1 16 55
1 17 51
1 18 4
1 19 17
1 20 20
1 21 4
1 22 4
1 23 6
1 24 12
2 1 6
2 2 22
2 3 0
2 4 0
2 5 33
2 6 5
2 7 4
2 8 8
2 9 28
2 10 99
2 11 51
2 12 66
2 13 38
2 14 39
2 15 60
2 16 22
2 17 65
2 18 50
2 19 22
2 20 11
2 21 12
2 22 9
2 23 33
2 24 13
3 1 5
3 2 8
3 3 44
3 4 0
3 5 12
3 6 2
3 7 5
3 8 12
3 9 34
3 10 43
3 11 54
3 12 44
3 13 40
3 14 48
3 15 54
3 16 59
3 17 60
3 18 51
3 19 21
3 20 16
3 21 9
3 22 5
3 23 24
3 24 7
4 1 22
4 2 33
4 3 102
4 4 33
4 5 0
4 6 2
4 7 4
4 8 13
4 9 26
4 10 58
4 11 61
4 12 59
4 13 53
4 14 54
4 15 64
4 16 55
4 17 52
4 18 53
4 19 18
4 20 3
4 21 9
4 22 12
4 23 2
4 24 8
5 1 2
5 2 0
5 3 8
5 4 2
5 5 0
5 6 2
5 7 4
5 8 14
5 9 31
5 10 48
5 11 46
5 12 50
5 13 66
5 14 54
5 15 56
5 16 67
5 17 54
5 18 23
5 19 14
5 20 6
5 21 8
5 22 7
5 23 0
5 24 84
6 1 11
6 2 22
6 3 33
6 4 44
6 5 4
6 6 0
6 7 4
6 8 8
6 9 8
6 10 6
6 11 14
6 12 12
6 13 9
6 14 14
6 15 0
6 16 4
6 17 7
6 18 6
6 19 42
6 20 5
6 21 77
6 22 32
6 23 41
6 24 0
7 1 7
7 2 6
7 3 11
7 4 22
7 5 33
7 6 44
7 7 66
7 8 5
7 9 33
7 10 0
7 11 2
7 12 2
7 13 44
7 14 6
7 15 0
7 16 4
7 17 33
7 18 2
7 19 10
7 20 7
7 21 0
7 22 19
7 23 9
7 24 4
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<style>
rect.bordered {
stroke: #E6E6E6;
stroke-width:2px;
}
text.mono {
font-size: 9pt;
font-family: Consolas, courier;
fill: #aaa;
}
text.axis-workweek {
fill: #000;
}
text.axis-worktime {
fill: #000;
}
</style>
<script src="http://d3js.org/d3.v3.js"></script>
</head>
<body>
<div id="chart"></div>
<div id="dataset-picker">
</div>
<script type="text/javascript">
var margin = { top: 50, right: 0, bottom: 100, left: 30 },
width = 960 - margin.left - margin.right,
height = 430 - margin.top - margin.bottom,
gridSize = Math.floor(width / 24),
legendElementWidth = gridSize*2,
buckets = 9,
colors = ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"], // alternatively colorbrewer.YlGnBu[9]
days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
times = ["1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a", "12p", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p", "12a"];
datasets = ["data.tsv", "data2.tsv"];
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var dayLabels = svg.selectAll(".dayLabel")
.data(days)
.enter().append("text")
.text(function (d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) { return i * gridSize; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
.attr("class", function (d, i) { return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis"); });
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter().append("text")
.text(function(d) { return d; })
.attr("x", function(d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)")
.attr("class", function(d, i) { return ((i >= 7 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });
var heatmapChart = function(tsvFile) {
d3.tsv(tsvFile,
function(d) {
return {
day: +d.day,
hour: +d.hour,
value: +d.value
};
},
function(error, data) {
var colorScale = d3.scale.quantile()
.domain([0, buckets - 1, d3.max(data, function (d) { return d.value; })])
.range(colors);
var cards = svg.selectAll(".hour")
.data(data, function(d) {return d.day+':'+d.hour;});
cards.append("title");
cards.enter().append("rect")
.attr("x", function(d) { return (d.hour - 1) * gridSize; })
.attr("y", function(d) { return (d.day - 1) * gridSize; })
.attr("rx", 4)
.attr("ry", 4)
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", colors[0]);
cards.transition().duration(1000)
.style("fill", function(d) { return colorScale(d.value); });
cards.select("title").text(function(d) { return d.value; });
cards.exit().remove();
var legend = svg.selectAll(".legend")
.data([0].concat(colorScale.quantiles()), function(d) { return d; });
legend.enter().append("g")
.attr("class", "legend");
legend.append("rect")
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", gridSize / 2)
.style("fill", function(d, i) { return colors[i]; });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d); })
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height + gridSize);
legend.exit().remove();
});
};
heatmapChart(datasets[0]);
var datasetpicker = d3.select("#dataset-picker").selectAll(".dataset-button")
.data(datasets);
datasetpicker.enter()
.append("input")
.attr("value", function(d){ return "Dataset " + d })
.attr("type", "button")
.attr("class", "dataset-button")
.on("click", function(d) {
heatmapChart(d);
});
</script>
</body>
</html>

Copyright (c) 2016, Tom May

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.

@tommaybe
Copy link
Author

Hi - thanks!

Added a tooltip using the svg:title element. If you want something fancy you'll have to look at some tooltip plugins (tipsy or the one from bootstrap for example). :-)

@eddy1982
Copy link

Hi, thanks for sharing this.

Do you have any idea why heatmap doesn't appear on chrome right now? but it displays correctly on firefox. I used to see it on chrome.

@patricksurry
Copy link

I also discovered it doesn't display on Chrome (v 27.0.1453.93, OS X) but it works in Safari

@tommaybe
Copy link
Author

tommaybe commented Jun 8, 2013

Thanks for noticing!

Something told me sourcing colorbrewer from raw.github.com was a bad idea.

Anyways, it is fixed now!

@jpiaggio
Copy link

jpiaggio commented Jul 1, 2013

Greate example,
Is there a way to make an action when the user clicks ok a cell?

@farrukhsubhani
Copy link

you can use simple javascript to add actions on svg elements

@AAverin
Copy link

AAverin commented Sep 18, 2013

Hi. Thanks for the nice heatmap code.
I was reworking it for the project (scaling and coloring mostly), and noticed this:
var colorScale = d3.scale.quantile()
.domain([0, buckets - 1, d3.max(data, function (d) { return d.value; })])
.range(colors);

I was wondering why domain has 3 arguments?
In case of default 9 buckets and when value in data is very high (eg 300) it gives a domain of [0, 8, 300]. mapping that to a range results in a little strange looking distribution where half of the scale is between 0 and 8, and the rest is distributed from 8 to 300.

That also doesn't look good if you need to display a heatmap with only 0 values - some default state with no data present.

@liamjm
Copy link

liamjm commented Sep 25, 2013

Great work!

What licence is this released under? Any restrictions?

@tommaybe
Copy link
Author

@AAverin Thanks! I think this was a hack to counter the strange value distribution I had in my use-case. I have removed it in my use-case and you should too. :-)
@liamjm It's sample code so it's in the public domain - use it however you want. :-)

@zohaibmomin
Copy link

Does not work in IE8 .IE8 doesn't support SVG.
Any alternatives or suggestions??

Any easy fix in the same code would help a lot .

@tommaybe
Copy link
Author

@zohaibmomin: This is a D3 example, and D3 does not support IE8 or below.

@FreekKalter
Copy link

@AAverin You can pass the domain function of quantile the whole array of values. It will calculate a better distribution, even when the data is in the rage 100-200 (not starting from 0) for example. The line in question becomes this:

var colorScale = d3.scale.quantile()
        .domain(data.map(function(k){ return k.value}))
        .range(colors);

@serenaf
Copy link

serenaf commented Jul 11, 2014

Hi there, the heapmap is really beautiful, great work! I just have a question making it dynamic. Is there an easy way to update all cells, for example in our case we need to shift every cell to the left every x seconds (so the outermost left cell vanished). The transition should look smooth and not as if the page refreshes. Thanks for any input :)

@Saeven
Copy link

Saeven commented Sep 3, 2015

Very cool. Your middle noon label should be 12p and not 12a though! Small nitpick.

@parthaportfolio
Copy link

HI there am using your heat map in one of my project and i want to show the value in each box , how can i achieve it ?

@toenuff
Copy link

toenuff commented Feb 13, 2016

Would you mind applying a license so I can use this?

  1. code on the internet - even a sample is not automatically public domain
  2. public domain licenses are not allowed by most companies - legal departments do not like them
  3. I think what you want is something open and free like the MIT license - https://opensource.org/licenses/MIT

This blog post covers the problem and solutions: http://blog.rtwilson.com/please-specify-a-license-for-your-software-and-even-your-code-samples/

Please - I really like the sample and would like to use it! Thank you!

@curtiszimmerman
Copy link

Hey just wanted to say THANKS for this great piece of code! We're using it in a hackathon this weekend for our main visualization. :)

@RingoIngo
Copy link

This is really great! Helps me to visualize my data a lot!!
Still i would like to support @toenuff s petition for a license:)
(MIT would be wonderful)
Thank you

@oridanus
Copy link

Great one!
Maybe someone can help me?
I want to make the columns and rows dynamic. If, let's say, I don't have Sunday on the CSV, it won't show the row for Sunday. same with hours - if one hour doesn't have a value, don't show it.
It will be better to take the columns and rows titles from the CSV itself, and not hardcoded ( days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"] ).

I will really appreciate any help to get this great heatmap usable in my case.

Thanks!

@arjenmeijer
Copy link

Converting this to version 4 of d3.js runs into color problems. Does anybody got this working in version 4?

@masonhensley
Copy link

@tjdecke have you consider adding a specific license per @toenuff's request? MIT would be great!

Thanks, neat gist!

@tommaybe
Copy link
Author

@toenuff @masonhensley I've updated the gist with the MIT License. Sorry for not including this earlier.

@malik714
Copy link

A quick question, would it be possible to make it half hourly, instead of 24 boxes, we would have 48 half hours slots ?

@spk
Copy link

spk commented Feb 1, 2017

@tjdecke thanks for the gist, I had to adapt it to fix the title caption on the rect (when you have the mouse on the rec)
https://gist.github.com/spk/3c8f0e8ccd3ee5d84894298e9bb754ef/revisions#diff-eacf331f0ffc35d4b482f1d15a887d3bR95
This worked for me, cheers

@samshah777
Copy link

This is great ! I was looking to add a filter to this (such that only filtered values show). Any idea how this can be achieved ?

@ramya289
Copy link

ramya289 commented Oct 9, 2017

Hi,
Thanks for your heatmap. I want to use your heatmap in my project. But my project is based on Flask. In flask data.tsv not reflecting on index.html. Any idea how this can be achieved?

@jamesshapiro
Copy link

jamesshapiro commented Oct 17, 2017

When I download the project and open up index.html in my browser (Chrome), the boxes do not display. They do work in Chrome on your website however (http://bl.ocks.org/tjdecke/5558084). Any idea what's causing the discrepancy here?

screen shot 2017-10-16 at 7 59 57 pm

@mthompson9
Copy link

Hi, I am trying to reuse this code for a project I'm working on. I'm struggling to parse values from my own tsv file into this as a dataset?

Would you be be able to give me any help with this?

@volka96
Copy link

volka96 commented Jun 27, 2019

It seems that title is showing only after choosing data files (calling heatmapChart function).
I think you need to move your cards.append("title"); call after cards.enter().append("rect").
Heatmap is great by the way.

@ryandle
Copy link

ryandle commented Sep 6, 2019

Great gist! Your times array seems to have 12p / 12a flipped though. Shouldn't it be:

times = ["1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a", "12p", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p", "12a"];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment