Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@wboykinm
Forked from mbostock/.block
Last active September 5, 2017 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wboykinm/34627426d84f3242e0e6ecb2339e9065 to your computer and use it in GitHub Desktop.
Save wboykinm/34627426d84f3242e0e6ecb2339e9065 to your computer and use it in GitHub Desktop.
Custom Time Format
license: gpl-3.0

The date tick format shown here 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". This formatter must be implemented differently in D3 V4 now that the multi-format method has been deprecated. You can create your own custom multi-scale time format programatically, using the conditional handling example here.

<!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.v4.min.js"></script>
<script>
// Establish the desired formatting options using locale.format():
// https://github.com/d3/d3-time-format/blob/master/README.md#locale_format
var formatMillisecond = d3.timeFormat(".%L"),
formatSecond = d3.timeFormat(":%S"),
formatMinute = d3.timeFormat("%I:%M"),
formatHour = d3.timeFormat("%I %p"),
formatDay = d3.timeFormat("%a %d"),
formatWeek = d3.timeFormat("%b %d"),
formatMonth = d3.timeFormat("%B"),
formatYear = d3.timeFormat("%Y");
// Define filter conditions
function multiFormat(date) {
return (d3.timeSecond(date) < date ? formatMillisecond
: d3.timeMinute(date) < date ? formatSecond
: d3.timeHour(date) < date ? formatMinute
: d3.timeDay(date) < date ? formatHour
: d3.timeMonth(date) < date ? (d3.timeWeek(date) < date ? formatDay : formatWeek)
: d3.timeYear(date) < date ? formatMonth
: formatYear)(date);
}
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.scaleTime()
.domain([new Date(2015, 0, 1), new Date(2017, 0, 1)])
.range([0, width]);
// Use the custom scale
var xAxis = d3.axisBottom()
.scale(x)
.tickFormat(multiFormat);
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