metacubed
metacubed

Reputation: 7301

Show time durations on a d3 axis

I am currently creating a d3 axis using d3.time.scale.utc(). My input for the axis is a series of time offsets in minutes (with decimal values). For example:

var minuteOffsets = [0.03, 1.65, 3.22, ..., 89.91, 90.01];

I want to display these time offsets in mm:ss format on the axis. The axis labels can be at standard intervals, like so:

  +------+------+-- ... --+------+------+-- ... --+------+
00:00  00:30  01:00     59:30  60:00  60:30     90:00  90:30

Note specifically that the minute value should show values >60. The seconds value has the normal range 0-59.

When I tried using .tickFormat(d3.time.format('%M:%S')), it wraps the minute value back to 00:00 after the 45:00 label. I also had a look at duration from moment.js, but I can't figure out how exactly to incorporate that into my code.

Upvotes: 3

Views: 2315

Answers (1)

metacubed
metacubed

Reputation: 7301

Based on the comment by Lars Kotthoff, I changed my scale to be a linear scale, instead of a time scale. Then I added a custom tickFormat function to do the necessary formatting.

I used MomentJS to first create a duration from the minute values, and then used the library moment-duration-format to produce the tick label in mm:ss format.

var axis = d3.svg.axis().tickFormat(function (d) {
    return moment.duration(d, 'minutes')
                 .format('mm:ss', { trim: false });
});

This helps to avoid explicitly writing code for extracting the minute and second components, and then formatting them into a string.

Upvotes: 4

Related Questions