Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

javascript - D3 v4 - Get the value of the each tick present on an axis?

Using D3.js version 4, is there a way to get an array of the values for each tick on an axis?

Edit:

From D3 documentation

# axis.tickValues([values]) <>

If a values array is specified, the specified values are used for ticks rather than using the scale’s automatic tick generator. If values is null, clears any previously-set explicit tick values and reverts back to the scale’s tick generator. If values is not specified, returns the current tick values, which defaults to null.

I am using the automatic tick generator so if I call

var tickValues = axis.tickValues();

tickValues is null

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a reference to the axis, you can use:

axis.scale().ticks()

If you want them all formatted out, I'd get them from the DOM:

d3.selectAll(".tick>text")
  .nodes()
  .map(function(t){
    return t.innerHTML;
  })

Running code:

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>

var svg = d3.select("svg"),
    margin = {top: 20, right: 0, bottom: 20, left: 0},
    width = svg.attr("width") - margin.left - margin.right,
    height = svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scalePoint()
    .domain([0, 1, 2])
    .range([0, width])
    .padding(1);

var y = d3.scaleLinear()
    .domain([-1e6, 2e6])
    .range([height, 0]);

var axis = d3.axisLeft(y)
        .ticks(20, "s");
        
g.append("g")
    .attr("transform", "translate(" + x(0) + ",0)")
    .attr("class", "axis")
    .call(axis);
    
console.log(
  axis.scale().ticks()
);

console.log(
  d3.selectAll(".tick>text")
    .nodes()
    .map(function(t){
      return t.innerHTML ;
    })
);
    
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...