如何在页面中心对齐d3.linearScale()?

fra*_*pps 5 html javascript css svg d3.js

我正在尝试创建一个二维笛卡尔坐标系,其原点位于svg的中心。基本上像这样: 我想如何拥有它... 我目前的方法是平移轴,使轴的原点位于中间。

  // Add the x Axis
  svg.append("g")
      .attr("transform", "translate(" + 0 + "," + height/2 + ")")
      .call(d3.axisBottom(x).ticks(100));

  // Add the y Axis
  svg.append("g")
      .attr("transform", "translate(" + width/2 + "," + 0 + ")")
      .call(d3.axisLeft(y).ticks(100));
      });
Run Code Online (Sandbox Code Playgroud)

但是,我需要手动调整范围以使y轴居中。每个屏幕尺寸所需的值都不同,这就是为什么我需要弄清楚为什么总是将我的坐标轴放在每个屏幕上居中的原因。

  var x = d3.scaleLinear().range([width/2-5*width,width/2+5*width]).domain([-50, 50]); 
  var y = d3.scaleLinear().range([height/2-5*height,height/2+3.244*width]).domain([50,  -50]); //the value 3.244 is the problem, it changes on every screen
Run Code Online (Sandbox Code Playgroud)

我创建了一个Fiddle,以便向您展示我如何精确地创建了坐标轴。

fra*_*pps 1

好吧,我自己想出来了。关键是利用宽度与高度的关系。更新的 Fiddle 在这里

  var x = d3.scaleLinear().range([width/2-5000*width/height,width/2+5000*width/height]).domain([-50, 50]);
  var y = d3.scaleLinear().range([height/2-5000*width/height,height/2+5000*width/height]).domain([50,  -50]);
Run Code Online (Sandbox Code Playgroud)