Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active September 5, 2017 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mbostock/4149176 to your computer and use it in GitHub Desktop.
Save mbostock/4149176 to your computer and use it in GitHub Desktop.
Custom Time Format
license: gpl-3.0

The tick format provided by d3.time.scale is a multi-scale tick format, meaning that it formats times differently depending on the time. For example, the start of February is formatted as "February", while February second is formatted as "Feb 2". The format is implemented using an array of time formats, each with an associated filter. The first filter that returns true is used. (In the implementation below, the formats are processed in reverse order.) You can create your own custom multi-scale time format using d3.time.format.multi.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var customTimeFormat = d3.time.format.multi([
[".%L", function(d) { return d.getMilliseconds(); }],
[":%S", function(d) { return d.getSeconds(); }],
["%I:%M", function(d) { return d.getMinutes(); }],
["%I %p", function(d) { return d.getHours(); }],
["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }],
["%b %d", function(d) { return d.getDate() != 1; }],
["%B", function(d) { return d.getMonth(); }],
["%Y", function() { return true; }]
]);
var margin = {top: 250, right: 40, bottom: 250, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.time.scale()
.domain([new Date(2012, 0, 1), new Date(2013, 0, 1)])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.tickFormat(customTimeFormat);
var svg = d3.select("body").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 + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment