Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a custom axis formatter for hours & minutes in d3.js?

Tags:

label

d3.js

I've got a dataset I'm graphing with d3.js. The x axis represents time (in minutes). I'd like to display this axis in an hh:mm format, and I can't find a way to do this cleanly within d3.

My axis code looks like:

svg.append('g')
   .attr('class', 'x axis')
   .attr('transform', 'translate(0,' + height + ')')
   .call(d3.svg.axis()
     .scale(x)
     .orient('bottom'));

Which generates labels in minutes that looks like [100, 115, 130, 140], etc.

My current solution is to select the text elements after they've been generated, and override them with a function:

   svg.selectAll('.x.axis text')
   .text(function(d) { 
       d = d.toFixed();
       var hours = Math.floor(d / 60);
       var minutes = pad((d % 60), 2);
       return hours + ":" + minutes;
   });

This outputs axis ticks like [1:40, 1:55, 2:10], etc.

But this feels janky and avoids the use of d3.format. Is there a better way to make these labels?

like image 950
matthewsteele Avatar asked Jul 02 '12 01:07

matthewsteele


1 Answers

If you have absolute time, you probably want to convert your x data to JavaScript Date objects rather than simple numbers, and then you want to use d3.time.scale and d3.time.format. An example of "hh:mm" format for an axis would be:

d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(d3.time.format("%H:%M"));

And actually, you may not need to specify a tick format at all; depending on the domain of your scale and the number of ticks, the default time scale format might be sufficient for your needs. Alternatively, if you want complete control, you can also specify the tick intervals to the scale. For example, for ticks every fifteen minutes, you might say:

d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(d3.time.minutes, 15)
    .tickFormat(d3.time.format("%H:%M"));

If you have relative time, i.e. durations, (and hence have numbers representing minutes rather than absolute dates), you can format these as dates by picking an arbitrary epoch and converting on-the-fly. That way you can leave the data itself as numbers. For example:

var formatTime = d3.time.format("%H:%M"),
    formatMinutes = function(d) { return formatTime(new Date(2012, 0, 1, 0, d)); };

Since only the minutes and hours will be displayed, it doesn't matter what epoch you pick. Here’s an example using this technique to format a distribution of durations:

  • http://bl.ocks.org/3048166
like image 124
mbostock Avatar answered Nov 15 '22 03:11

mbostock