How can I get the D3.js axis ticks and positions as an array?

前端 未结 2 1670
醉梦人生
醉梦人生 2021-01-07 17:20

I usually place my axis ticks on the svg using this:

d3.svg.axis().scale(xScale(width)).ticks(4)

Is it possible to get these tick values a

相关标签:
2条回答
  • 2021-01-07 17:47

    In d3 v4 I ended up just parsing the rendered x values from the tick nodes

    function parseX(transformText) {
        let m = transformText.match(/translate\(([0-9\.]*)/);
        let x = m[1];
        if (x) {
            return parseFloat(x);
        }
    }
    
    0 讨论(0)
  • 2021-01-07 18:10

    Yes, xScale.ticks(4) should give you the actual tick points as values, and you can pipe those back through your xScale to the the X position. You can also just pull the tick points back from the generated elements after you apply the axis to an actual element:

    var svg = d3.select("svg");
    
    var scale = d3.scale.linear()
        .range([20, 280])
        .domain([0, 100])
    
    var axis = d3.svg.axis().scale(scale).orient("bottom").ticks(9);
    // grab the "scale" used by the axis, call .ticks()
    // passing the value we have for .ticks()
    console.log("all the points", axis.scale().ticks(axis.ticks()[0]));
    // note, we actually select 11 points not 9, "closest guess"
    
    // paint the axis and then find its ticks
    svg.call(axis).selectAll(".tick").each(function(data) {
      var tick = d3.select(this);
      // pull the transform data out of the tick
      var transform = d3.transform(tick.attr("transform")).translate;
    
      // passed in "data" is the value of the tick, transform[0] holds the X value
      console.log("each tick", data, transform);
    });
    

    jsbin

    0 讨论(0)
提交回复
热议问题