How to align d3.linearScale () in the center of the page?

I am trying to create a 2D Cartesian coordinate system with its origin in the center of svg. Basically this: How I wish ... My current approach is to translate the axes so that their origin is in the middle.

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

However, I need to adjust the range manually so that the Y axis is centered. The required value is different from each screen size, so I need help figuring out how to always get the coordinate axes centered on each screen.

  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

I created Fiddle to show you exactly how I created the coordinate axes.

+4
source share
2 answers

, . . .

  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]);
0

(, , ? : https://jsfiddle.net/smftm5sv/).

SVG . -, , ... :

var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([0, height]);

-, , (y(0) x(0)). x y , :

svg.append("g")
    .attr("transform", "translate(0"," + y(0) + ")")
    .call(d3.axisBottom(x));

svg.append("g")
    .attr("transform", "translate(" + x(0) + ",0)")
    .call(d3.axisLeft(y));

(, jQuery, jQuery D3):

var width = window.innerWidth;
var height = window.innerHeight;
var padding = 10;


  var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(d3.zoom().on("zoom", function() {
      svg.attr("transform", d3.event.transform);
    }))
    .append("g");

  var viewport = svg.append('g');

  var x = d3.scaleLinear().range([0 + padding, width - padding]).domain([-50, 50]); 
  var y = d3.scaleLinear().range([0 + padding, height - padding]).domain([50, -50]);

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

  // Add the y Axis
  svg.append("g")
    .attr("transform", "translate(" + x(0) + "," + 0 + ")")
    .call(d3.axisLeft(y));
<script src="https://d3js.org/d3.v4.min.js"></script>

( ), y , x .

+1

Source: https://habr.com/ru/post/1690177/


All Articles