【问题标题】:Get offset position of an axis tick获取轴刻度的偏移位置
【发布时间】:2016-02-03 11:09:27
【问题描述】:

我有一个范围为 1-10 的线性刻度,x 轴为每个数字绘制一个刻度。

我希望能够找出 x 轴上刻度线的偏移位置。有没有办法做到这一点?我希望能够调用某些东西并喂它 一个介于 1 和 10 之间的数字,并返回刻度的偏移位置。我可以使用这个普通的 js,但我想知道是否有以 d3 为中心的方式 这样做?

var x = d3.scale.linear()
        .domain(d3.extent(data), (function(d,i) { return d.year; })))
        .range([0, width]);


    var xAxis = d3.svg.axis()
        .scale(x)
        .tickSize(-height)
         .tickFormat("")
        .tickPadding(10)  
        .tickSubdivide(true)  
        .orient("bottom");

【问题讨论】:

  • 你想要关于轴上 0,0 的偏移量?
  • 是的,应该提到这一点。
  • 你有任何代码来显示你如何创建刻度等吗?
  • 是的,已在上面更新。我只是使用标准的 d3 轴

标签: d3.js


【解决方案1】:

超级hacky选项:

将 id 添加到轴:

g.append("g").attr('id','xAxis').attr("class", "x axis")

创建函数以传递值以获取偏移量:

function getAxisTick(axis, number) {
    if (axis === 'x') { //check what axis you want
      var thisXAxis = document.getElementById('xAxis'); //get xAxis
      //below you get the transform value of the tick you want depending on number you pass
      //so you get the children of the xAxis i.e ticks and get their transform value
      var children = thisXAxis.children[number].attributes.transform.nodeValue

      //as children is the whole translate string, i.e 'translate(124.555,0)' etc we have to split it
      //we know the x value is from index 10 to the first comma
      var thisXPos = children.substring(10, children.lastIndexOf(","));
      //return split string
      return thisXPos;


    } else if (axis === 'y') {
      var thisXAxis = document.getElementById('yAxis');
      var children = thisXAxis.children[number].attributes.transform.nodeValue;
      //we know the y value is from index 12 (as all x values are 0) to the first ')'
      var thisYPos = children.substring(12, children.lastIndexOf(")"));
      // console.log(thisYPos)

      return thisYPos;
    }

  }

我们现在要做的就是在哪个轴上选择你想要的刻度:

  var xTick2 = getAxisTick('x', 2)
  var yTick4 = getAxisTick('y', 4)
  console.log(xTick2);
  console.log(yTick4);

工作小提琴:http://jsfiddle.net/oh7wjs45/22/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2013-01-20
    • 1970-01-01
    相关资源
    最近更新 更多