1

I created an XAXIS using d3.axisBottom(). Now I need to store the positions (x and y attributes of the tick text) in a separate variable.

My full code is at codepen https://codepen.io/zubair57/pen/gOLeeOm

When I use below code to get "x and y" attributes, I get value for y attr but null for x attr. Could you tell me why I get null for x attr and how to get correct value

d3.select(".xaxis").selectAll(".tick text").each(function(d,i){
    let me=d3.select(this)  
    console.log(me.attr("x"))
    console.log(me.attr("y"))
})
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
Zubair
  • 119
  • 8

1 Answers1

1

In D3 the axis generator creates several groups translated along the x axis (in the case of d3.axisBottom()), and then the texts have only the y position set. For instance, in your axis:

<g class="tick" opacity="1" transform="translate(50.5,0)">
<!-- x translated here ---------------------------^  -->
    <line stroke="currentColor" y2="0" style="stroke: black; stroke-width: 2;"></line>
    <text fill="currentColor" y="3" dy="0.71em" style="fill: black; font-size: 20px; font-family: Arial;">1</text>
</g>
etc...

Therefore, there is no x attribute to get.

For getting the x position of the text you have to select their parents, which are this.parentNode. However, using methods like getBBox() won't work because the element is translated. You could use d3.transform() in v3, but it was removed in D3 v4 and above. For a workaround, please check this answer: https://stackoverflow.com/a/38230545/5768908

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171