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

后端 未结 2 1731
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 00:37

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

相关标签:
2条回答
  • 2021-01-18 01:27

    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>

    0 讨论(0)
  • 2021-01-18 01:28

    I found the answer of Mark above was not correct for my case, I changed a bit from his inspiration and it worked

    // I am using d3-scale
    const yScale = scaleLinear().domain(realYDomain).range([30, 170]);
    // I am using d3-axis
    const yAxis = axisLeft(yScale); // Not declare axisLeft(scale).ticks(number) here, but below line instead
    const tickValues = yAxis.scale().ticks(5);
    console.log(tickValues);
    
    0 讨论(0)
提交回复
热议问题