Search code examples
d3.jsscale

D3: Convert scale level of the time scale to time period, like: day, week or month?


Having the current scale level for the time scale from d3.event.scale (e.g. 0.5 or 1.5), is there any rule of how to convert it to human readable form, like - day, week, month or year?

UPDATE:

Here is a draft of what I'm working on: http://cdpn.io/gzfyj. I'm basically seeking for a way to get time boundaries after zooming or panning and the zoom factor in above mentioned identifiers.


Solution

  • After zooming,

    var width = x.domain(); 
    var dur = width[1] - width[0]; 
    

    will return the width of the scale in milliseconds. Then this duration can be converted to any form you like.


    This is an working example where I have used moment.js to humanize the duration at the bottom of the graph: http://codepen.io/musically_ut/pen/DJqtw

      var ext = x.domain();
      var duration = moment.duration(ext[1] - ext[0]).humanize();
    
      chart
        .select("text.duration")
        .text(duration);