Mike Rifgin
Mike Rifgin

Reputation: 10757

Get offset position of an axis tick

I have a linear scale ranging from 1-10 and x axis plotting out a tick for each number.

I want to be able find out the offset position for a tick on the x axis. Is there any way of doing this? I'd like to be able to call something and feed it a number between 1 and 10 and get back the offset position of the tick. I could do with this plain js but I'm wondering if there's a d3-centric way of doing this?

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");

Upvotes: 3

Views: 1329

Answers (1)

thatOneGuy
thatOneGuy

Reputation: 10622

Super hacky option :

Add id to axis :

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

Create function to pass values to to get offset :

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;
    }

  }

All we have to do now is chose what tick you want on which axis :

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

Working fiddle : http://jsfiddle.net/oh7wjs45/22/

Upvotes: 3

Related Questions