Search code examples
javascriptd3.jsrescale

d3.js get new domain values after rescale


I try to get the new axes values after rescaling my axes.

I tried to get them from y.domain() as answered here but the values returned are the initial values.

So what am i doing wrong here?

Relevant code:

function zoomed() {

  for(let i = 0; i < ys.length; i++){
    yAxes[i].call(
      d3.axisLeft(ys[i])
        .scale(d3.event.transform.rescaleY(ys[i]))
    )
  }

  //Now I need the new values

  console.log(ys[0].domain()) //returns [0, 10] which are my initial domain values for this axis.

}

After zooming, the values i have on screen are bigger than 0 and smaller than 10. So how do i get my domains new min and max values?

Here is a fiddle with an older version of my code, which has the exact same behavior (see zoomed() function).

Maybe I misunderstand what the domain is and how it works, what I need are the new max and min values of my axis.


Solution

  • basing my answer on this code from the fiddle:

      function zoomed() {
        let center = getBoundingBoxCenterX(rect);
        let chartsWidth = (2 * center) * d3.event.transform.k;
        d3.event.transform.x = center - chartsWidth / 2;
        xAxis.call(d3.axisBottom(x).scale(d3.event.transform.rescaleX(x)));
        yAxis.call(d3.axisLeft(y).scale(d3.event.transform.rescaleY(y)));
        zAxis.call(d3.axisRight(z).scale(d3.event.transform.rescaleY(z)));
    
        //here i need the new values
        console.log(y.domain()) //returns [0,6]
    

    Edit

    You can get the axis scale this way:

    let leftAxis = d3.axisLeft(y).scale(d3.event.transform.rescaleY(y));
    console.log('new domain values', leftAxis.scale().domain())
    

    I've got a version of the fiddle with this working: https://jsfiddle.net/aj5sLz5u/