D3.js time scale: nicely-spaced ticks at minute intervals when data is in seconds?

前端 未结 1 1731
既然无缘
既然无缘 2021-02-03 11:16

I\'m working with a D3 time scale. My input data is in seconds, and it\'s duration data rather than dates - so 10 seconds, 30 seconds etc.

I want to create an axis that

1条回答
  •  别那么骄傲
    2021-02-03 11:44

    Normally when making a time scale, you would use d3.time.scale(), rather than a linear scale.

    Your case is a little odd in that you are using abstract durations of time, and not specific points in time for your data. Unfortunately it seems that d3's built in time functionality is not well-suited to this case. There are a couple of options I can think of for workarounds:


    Option 1: Use a linear scale with manual .tickValues()

    Rather than formatting your ticks using a Date object. You could simply break down your data value (which is in seconds) into hours, minutes, and seconds. Something like this:

    formatMinutes = function(d) { 
        var hours = Math.floor(d / 3600),
            minutes = Math.floor((d - (hours * 3600)) / 60),
            seconds = d - (minutes * 60);
        var output = seconds + 's';
        if (minutes) {
            output = minutes + 'm ' + output;
        }
        if (hours) {
            output = hours + 'h ' + output;
        }
        return output;
    };
    

    Basically, this takes the total number of seconds, creates an hour for every 3600 seconds, creates a minute for each remaining 60 seconds, and finally gives back the remaining seconds. Then it outputs a string representation, for example: 17s or 12m 42s or 4h 8m 22s.

    Then when you make your axis, you can use the .tickValues() method to assign a range from zero to your data's max value, going by steps of 600, since there are 600 seconds in 10 minutes. That would look like this:

    var x = d3.scale.linear()
      .domain([0, d3.max(values)])
      .range([0, width]);
    
    var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom")
      .tickFormat(formatMinutes)
      .tickValues(d3.range(0, d3.max(values), 600));
    

    Here's a JSFiddle of the output.


    Option 2: Use a time scale with a fixed duration for .ticks()

    Time scales let you specify directly that you'd like ticks every 10 minutes. You do that simply by passing a d3 duration and a multiplier to the .ticks() method of your axis. Like this:

    var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom")
      .ticks(d3.time.minute, 10)
    

    In order to do this, you must first set up your time scale. For the domain of your scale, you can use a range of millisecond values, since d3 will turn these into Date objects. In this case, since your data is in seconds, we can simply multiply by 1000 to get milliseconds. In this case we'll round up the max value to the nearest millisecond, since it must be an integer to make a valid date:

    var x = d3.time.scale()
      .domain([0, Math.ceil(d3.max(values) * 1000)])
      .range([0, width]);
    

    Finally, you can pass your format in directly to the axis, using .tickFormat():

    var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom")
      .ticks(d3.time.minute, 10)
      .tickFormat(d3.time.format('%Mm %Ss'));
    

    However, at this point I need to point something out because, as I mentioned, the built-in time functions are not well-suited to dealing with abstract durations. I'm going to change the .tickFormat to show the hours as well:

    .tickFormat(d3.time.format('%Hh %Mm %Ss'));
    

    Have a look at the JSFiddle of what the result would be...

    Depending on where you are in the world, you'll get a different value for the hours place. I'm on the East coast of the US, so my hours place says 19. Where is that coming from? Shouldn't it be zero?

    Well, unfortunately, when we made the domain of the scale go from 0 to the number of milliseconds of the largest data value, it created regular Date objects, using those values for the millisecond input. This means that they represent the number of milliseconds since midnight UTC time on January 1, 1970. Here in the Eastern time zone of the US, that means it was 19:00:00 on December 31, 1969. That's where the 19 comes from, or whatever other value you get.

    If you know that all of your data will be less than 1 hour, then perhaps you can just ignore this. If you need to use an hours place, you can work around this by forcing d3 to use UTC time to format the axis using d3.time.format.utc():

    .tickFormat(d3.time.format.utc('%Hh %Mm %Ss'))
    

    Here's the JSFiddle updated to use UTC.

    Now you can see that the hour is 0 as expected.

    Of course, if any of your data is ever longer than 24 hours, this method won't work at all, and you'll have to resort to doing the axis manually as in Option 1.


    Hopefully this helps to at least get you started, it's a tricky problem though, and there doesn't seem to be an elegant solution built into the library for handling this. Perhaps it would make for a good feature request on d3's git repo. I'd love to hear if @mbostock has any suggestions on how to handle abstract durations of time in d3 without having to be tied to Date objects, which require references to absolute points in time.

    0 讨论(0)
提交回复
热议问题