Thomas Murphy Thomas Murphy - 3 months ago 34
Javascript Question

d3js - Generate custom labels from linearScale ticks

On a simple timeline in d3js, I'm generating my xAxis like so.

xScale = d3.scaleLinear()
.domain([0, 2500])
.range([leftPad, width - rightPad]);

var xAxis = d3.axisBottom();
xAxis.scale(xScale);


My domain represents the number of seconds since the timeline began, however I want to display my ticks in : format. Generating that string is simple enough:

var seconds = 370; //for example
var final_seconds = seconds % 60
var minutes = (seconds - final_seconds) / 60
var tick_text = minutes.toString() + ":" + final_seconds.toString()


My question is how to replace the text displayed below each tick in d3 with the computer value from the above code.

Answer

You have to put your code inside tickFormat:

.tickFormat(function(d){
    var seconds = d;  
    var final_seconds = seconds % 60
    var minutes = (seconds - final_seconds) / 60
    var tick_text = minutes.toString() + ":" + final_seconds.toString();
    return tick_text;
});

In this snippet, your domain (from 0 to 2500 seconds) goes from 0:00 to 40:00 (actually, 41 minutes and some seconds). Click "run code snippet":

var svg = d3.select("body")
    .append("svg")
    .attr("width", 500)
    .attr("height", 200);

xScale = d3.scaleLinear()
    .domain([0, 2500])
    .range([20, 480]);

var xAxis = d3.axisBottom(xScale)
    .tickFormat(function(d){
      var seconds = d; 
var final_seconds = seconds % 60;
var minutes = (seconds - final_seconds) / 60;
var tick_text = minutes.toString() + ":" + ("0" + final_seconds).slice(-2);
      return tick_text;
      });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0,100)")
    .call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: To make 0 second show up as 00, I made a slight change to your code, changing final_seconds to this:

("0" + final_seconds).slice(-2)