如何为小时和时间制作自定义轴格式化程序d3.js 的分钟数? [英] How do I make a custom axis formatter for hours & minutes in d3.js?

查看:21
本文介绍了如何为小时和时间制作自定义轴格式化程序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?

解决方案

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:

这篇关于如何为小时和时间制作自定义轴格式化程序d3.js 的分钟数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆