如何将D3.js轴刻度和位置作为数组?

el_*_*_le 24 d3.js

我通常使用以下方法将我的轴标记放在svg上:

d3.svg.axis().scale(xScale(width)).ticks(4)
Run Code Online (Sandbox Code Playgroud)

是否可以获取这些刻度值及其svg坐标,以便我可以使用svg外的自定义轴d3.svg.axis()

gna*_*arf 27

是的,xScale.ticks(4)应该将实际的刻度点作为值给出,并且可以将它们通过您的管道传递xScale到X位置.将轴应用于实际元素后,您也可以从生成的元素中拉回刻度点:

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);
});
Run Code Online (Sandbox Code Playgroud)

jsbin