Skip to content

Instantly share code, notes, and snippets.

@devgru
Last active October 27, 2019 19:18
Show Gist options
  • Save devgru/10488877 to your computer and use it in GitHub Desktop.
Save devgru/10488877 to your computer and use it in GitHub Desktop.
Heatmap
license: mit
<html>
<body>
<style>
svg {
width: 100%;
height: 240px;
}
g text {
font-size: 0.8em;
text-anchor: middle;
}
g text.first {
text-anchor: start;
}
g text.last {
text-anchor: end;
}
</style>
<script type='text/javascript' src='http://d3js.org/d3.v4.min.js'></script>
<script>
var url = "https://api.github.com/repos/mbostock/d3/stats/punch_card"
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
var color = d3.scaleLinear()
.range(['#FEFEFF', 'blue'])
.interpolate(d3.interpolateHcl)
d3.json(url, function (data) {
color.domain(d3.extent(data, function (d) { return d[2] }))
var body = d3.select('body')
var svg = body.append('svg')
var heatmap = svg
.append('g')
.attr('transform', 'translate(30,30)')
var span = svg
.append('text')
.attr('y', 11.5 * 20)
.attr('x', 30)
var head = svg
.append('g')
.attr('transform', 'translate(30,22)')
head
.append('text')
.classed('first', true)
.text('midnight')
head
.append('text')
.attr('x', 12 * 20)
.text('noon')
head
.append('text')
.classed('last', true)
.attr('x', 24 * 20)
.text('midnight')
heatmap
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', function (d) { return d[1] * 20 })
.attr('y', function (d) { return d[0] * 20 })
.attr('width', 20)
.attr('height', 20)
.style('fill', function (d) { return color(d[2]) })
.on('mouseover', function (d) {
span.text(d[2] + ' commits between ' + d[1] + ':00 and ' + d[1] + ':59 at ' + days[d[0]])
})
.on('mouseout', function (d) {
span.text('')
})
var dates = d3.nest()
.key(function (d) { return d[0] })
.entries(data)
var hours = d3.nest()
.key(function (d) { return d[1] })
.entries(data)
var daysMean = dates.map(function (v) {
return d3.mean(v.values, function(d) { return d[2] })
})
var hoursMean = hours.map(function (v) {
return d3.mean(v.values, function(d) { return d[2] })
})
svg.append('g')
.attr('transform', 'translate(' + (30 + 20 * 24 + 5) + ',30)')
.selectAll('rect')
.data(daysMean)
.enter()
.append('rect')
.attr('width', 20)
.attr('height', 20)
.attr('y', function (d, i) { return i * 20 })
.style('fill', color)
svg.append('g')
.attr('transform', 'translate(30,' + (30 + 20 * 7 + 5) + ')')
.selectAll('rect')
.data(hoursMean)
.enter()
.append('rect')
.attr('width', 20)
.attr('height', 20)
.attr('x', function (d, i) { return i * 20 })
.style('fill', color)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment