D3 punchcard
var D3punchcard = function(el, options) { | |
options || (options = {}); | |
var _chart = {}; | |
var _svg = null; | |
var _this = this; | |
_this.el = el | |
_this.data = options.data; | |
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; | |
var w = parseInt(d3.select(el).style('width'), 10); | |
var h = parseInt(d3.select(el).style('height'), 10) - 20; | |
var pad = 20; | |
var leftPad = 100; | |
var x = d3.scale.linear().domain([0, 23]).range([leftPad, w - pad]); | |
var y = d3.scale.linear().domain([0, 6]).range([pad, h - pad * 2]); | |
var xAxis = d3.svg.axis().scale(x).orient('bottom') | |
.ticks(24) | |
.tickFormat(function (d, i) { | |
var m = (d >= 12) ? 'p' : 'a'; | |
return (d % 12 == 0) ? 12 + m : d % 12 + m; | |
}); | |
var yAxis = d3.svg.axis().scale(y).orient('left') | |
.ticks(7) | |
.tickFormat(function (d) { return days[d]; }); | |
var maxRadius = d3.max(_this.data.map(function (d) { return d[2]; })); | |
var r = d3.scale.linear().domain([3, maxRadius]).range([0, 12]); | |
_chart.render = function() { | |
console.log('render'); | |
_svg = d3.select('#punchcard') | |
.html('') | |
.append('svg') | |
.attr('width', w) | |
.attr('height', h); | |
_svg.append('g') | |
.attr('class', 'x axis') | |
.attr('transform', 'translate(0, '+ (h - pad) +')') | |
.call(xAxis); | |
_svg.append('g') | |
.attr('class', 'y axis') | |
.attr('transform', 'translate('+ (leftPad - pad) +', 0)') | |
.call(yAxis); | |
_svg.selectAll('circle') | |
.data(_this.data) | |
.enter() | |
.append('circle') | |
.attr('class', 'circle') | |
.attr('cx', function (d) { return x(d[1]); }) | |
.attr('cy', function (d) { return y(d[0]); }) | |
.transition() | |
.duration(800) | |
.attr('r', function (d) { return r(d[2]); }); | |
}; | |
d3.select(window).on('resize', function() { | |
w = parseInt(d3.select(el).style('width'), 10); | |
h = parseInt(d3.select(el).style('height'), 10) - 20; | |
x.range([leftPad, w - pad]); | |
y.range([pad, h - pad * 2]); | |
_svg | |
.attr('width', w) | |
.attr('height', h); | |
_svg.select('.x.axis') | |
.attr('transform', 'translate(0, '+ (h - pad) +')') | |
.call(xAxis); | |
_svg.select('.y.axis') | |
.call(yAxis); | |
//var circles = _svg.select('.circle') | |
// .data(_this.data) | |
// .enter(); | |
}); | |
return _chart; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment