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.
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)
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.