【问题标题】:How can I get the D3.js axis ticks and positions as an array?如何将 D3.js 轴刻度和位置作为数组获取?
【发布时间】:2014-03-28 20:49:55
【问题描述】:

我通常使用以下方法将轴刻度放在 svg 上:

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

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

【问题讨论】:

  • 如果你打电话给xScale.ticks(),你应该得到它们。

标签: d3.js


【解决方案1】:

是的,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);
});

jsbin

【讨论】:

  • 什么是 v4 等价物?
  • 我还不确定自己,我还没有解决这个问题,但如果有人确实有 v4 equiv,请随时编辑/修改答案。
  • 已插入附录以使用 v4 获取 tickValues。
  • A D3 v4 answer is here(tldc;它是axis.scale().ticks(),或者只是someScaleObject.ticks() if the scale obj is accessible
  • d3 v4 中的 axis.scale().ticks() 可能会返回错误的刻度数。我设置了 5 个刻度,但它返回 11。
【解决方案2】:

在 d3 v4 中,我最终只是从刻度节点解析渲染的 x 值

function parseX(transformText) {
    let m = transformText.match(/translate\(([0-9\.]*)/);
    let x = m[1];
    if (x) {
        return parseFloat(x);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    相关资源
    最近更新 更多