Home > database >  D3 axis: set domain based on numbers but display them as strings
D3 axis: set domain based on numbers but display them as strings

Time:12-14

I have for dataset an array of objects like so

[
 {
  time: '20:07',
  seconds: 7620,
  value: 49,995
 },
 ...
]

I'm currently creating X axis like so

this.x = d3.scaleLinear()          
      .domain(this.values.map(function(d) { return d.seconds}))
      .range([ 0, width])
              
this.chart.append('g')
  .call(d3.axisBottom(this.x))

what happens now is following current x axis

so this correct domain, 7620 is smallest seconds value and 7800 highest, but now instead of showing seconds I wish to display 'time' value. First label on x axis would be then '20:07' instead of 7620.

In a nutshell, create domain based on seconds but show time instead. How can I do that ?

CodePudding user response:

You can transform the tick labels using tickFormat:

this.chart.append('g')
  .call(d3.axisBottom(this.x).tickFormat(d3.timeFormat("%H:%M")))
  • Related