score:54

Accepted answer

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:


Related Query

More Query from same tag