A custom axis function that "extends" the native axis (in this case, highlighting years on a time scale). See this Stack Overflow question.
Last active
August 29, 2015 14:18
-
-
Save HerbCaudill/ece2ff83bd4be586d9af to your computer and use it in GitHub Desktop.
Extending the d3 Axis function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="description" content="Extending the d3 Axis function"> | |
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<meta charset="utf-8"> | |
<title>Extending the d3 Axis function</title> | |
<style> | |
body { | |
font-family: sans-serif; | |
font-size: 10px; | |
} | |
.tick { | |
fill: gray; | |
} | |
.year { | |
fill: black; | |
font-weight: bold; | |
font-size: 11px; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="chart"></div> | |
<script> | |
$(function () { | |
var rebindAll = function (target, base) { | |
for (var key in base) { | |
if (base.hasOwnProperty(key)) { | |
d3.rebind(target, base, key); | |
} | |
} | |
}; | |
var timeAxis = function () { | |
var base = d3.svg.axis(); | |
isYear = function (d) { | |
return (d.getMonth() === 0); | |
}; | |
// Select and apply a style to your tick marks | |
var me = function (selection) { | |
selection.call(base); | |
selection | |
.selectAll('.tick', this) | |
.classed("year", isYear); | |
}; | |
rebindAll(me, base); | |
return me; | |
}; | |
var margin = { top: 20, left: 20, bottom: 20, right: 20 }; | |
var w = 500; | |
var h = 500; | |
var startDate = new Date('2010-07-13'); | |
var endDate = new Date('2012-04-01'); | |
var dateFormatter = d3.time.format.multi([ | |
['%b', function (d) { return d.getMonth(); }], | |
['%Y', function (d) { return true; }], | |
]); | |
var xScale = d3.time | |
.scale() | |
.domain([startDate, endDate]) | |
.range([0, 500]) | |
.nice(); | |
var xAxis = timeAxis() | |
.scale(xScale) | |
.tickPadding(10) | |
.ticks(10) | |
.tickFormat(dateFormatter); | |
svg = d3.select("#chart") | |
.append("svg") | |
.attr("height", h + margin.top + margin.bottom) | |
.attr("width", w + margin.left + margin.right); | |
canvas = svg.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); | |
xAxisElement = canvas.append("g") | |
.classed("axis x", true) | |
.call(xAxis); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment