获取轴刻度的偏移位置

时间:2016-02-03 11:09:27

标签: d3.js

我有一个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");

1 个答案:

答案 0 :(得分:3)

超级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/