简体   繁体   中英

D3 - format elapsed time

I'm new to d3.js but I really think this is a really powerful tool.

My problem today is formatting the time ticks.

I am having a live chart plotted with d3v5, with the time in the x-axis. The time is coded in milliseconds since the start of the page (time=0 after loading). I would like the ticks to show 15s,30s,45s,:1,15s,30s,45s,:2,and so on.

My problem is, using the scaletime function, I actually end up with the year 1970 shown at the start.

Can anyone guide me? I have started to look at the formattick function, but didn't end up finding a way to do what I wish.

Can anyone show me a direction?

Thank you,

I managed to find a solution by myself in the end.

I have changed my scale from timescale to scalelinear. I have created a function that return the proper d3.format value based on an input integer

      var TimeFormatLive = function(d) {
    if (d < 0) {//checking a condition based on that do foarmat
      //provide a format
      return '';
    }
    else if (d ==0){
      //provide some other format  
      return ":" + d3.format(".0f")(d/1000);
  }
    else if (d % (3600*1000)==0){
        //provide some other format  
        return d3.format(".0f")(d/(3600*1000)) + "h"; 
    }
    else if (d % (60*1000)==0){
          //provide some other format  
          return d3.format(".0f")((d /(1000*60)) % 60) + "min"; 
    }
    else {
     //provide some other format  
     return ":" + d3.format(".0f")((d/1000) % 60 ) ; 
    }
  };

I then apply this "filter" to my.tick object

.call(d3.axisBottom(x).ticks(15).tickFormat(TimeFormatLive)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM