Scaling the y axis up, while scaling the x axis down with D3.js

Viewed 109

I am building an interactive figure to show the scale invariance of the 1/r function in javascript with D3.js. To do this, I need to scale the figure in the x-direction by a factor of k and in the y-direction by a factor of 1/k. To do this I can access the d3.event.transform and manually set the k factor for the y axis like so:

var newxScale = d3.event.transform.rescaleX(xScale)
// this does not feel good, neither does it really work
d3.event.transform.k = 1/ d3.event.transform.k
var newyScale = d3.event.transform.rescaleY(yScale)
d3.event.transform.k = 1/ d3.event.transform.k

as demonstrated in this fiddle: https://jsfiddle.net/od9pcnut/44/

Changing the variables in the d3.event.transform feels incredibly wrong and messes up the zoom around the mouse position (the drawn line drifts off in some direction when I scale the figure). How can I tell the scale to scale by different factors in different directions, while retaining the zoom around mouse position feature?

1 Answers

d3.event.transform is an instance of d3.zoomIdentity. You can build a new zoom Identity and rescale the X / Y scales with it:

const {x, y, k} = d3.event.transform; 

const newxScale = d3.zoomIdentity
  .translate(x, y)
  .scale(k)
  .rescaleX(xScale);

const newyScale = d3.zoomIdentity
  .translate(x, y)
  .scale(1 / k)
  .rescaleY(yScale);
Related