JSFiddle - React, Tailwind, and code Playground
by Cyril Cherian
CSS
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
JavaScript
var data = [{
"date": "2012-03-20",
"total": 3,
"initiative": 0
}, {
"date": "2012-03-21",
"total": 8,
"initiative": 0
}, {
"date": "2012-03-22",
"total": 2,
"initiative": 1
}, {
"date": "2012-03-23",
"total": 10,
"initiative": 1
}, {
"date": "2012-03-24",
"total": 3,
"initiative": 2
}, {
"date": "2012-03-25",
"total": 20,
"initiative": 2
}];
var ordinals = ["a", "b", "c"];
var margin = {
top: 40,
right: 40,
bottom: 40,
left: 40
},
width = 600,
height = 500;
var x = d3.time.scale()
.domain([d3.time.day.offset(new Date(data[0].date), -1), d3.time.day.offset(new Date(data[data.length - 1].date), 1)])
.rangeRound([0, width - margin.left - margin.right]);
var yscale = d3.scale.linear()
.domain([0, ordinals.length])
.range([height - margin.top - margin.bottom, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.ticks(d3.time.days, 1)
.tickFormat(d3.time.format('%a %d'))
.tickSize(0)
.tickPadding(8);
var yAxis = d3.svg.axis()
.scale(yscale)
.orient('left')
.tickFormat(function(d) {
return ordinals[d];
})
.tickPadding(8);
var hideTicksWithoutLabel = function() {
//hide ticks without label
svg.selectAll(".y .tick")[0].forEach(function(g) {
if (d3.select(g).select("text").text() == "") {
d3.select(g).style("display", "none");
} else {
d3.select(g).style("display", "");
}
})
}
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
map.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
hideTicksWithoutLabel();
}
var zoom = d3.behavior.zoom()
.x(x)
.y(yscale)
.scaleExtent([1, 20])
.on("zoom", zoomed);
var svg = d3.select('body').append('svg')
.attr('class', 'chart')
.attr('width', width)
.attr('height', height)
.attr('transform', 'translate(' + margin.left + ',' + margin.bottom + ')')
.call(zoom);
var group =...