d3.js - D3 axis ticks and grid lines do not align -


i make plot 1 vertical , 1 horizontal grid line cross (0,0) point. have following script unfortunately axis ticks , origins of grid lines not align properly. source of discrepancy , how can fix this?

<!doctype html> <meta charset="utf-8">  <script src="d3.min.js"></script>  <body>  </body>  <script>  var margin = {top: 60, right: 60, bottom: 60, left: 70},     width = 550,     height = 550;  var svg = d3.select('body').append('svg')                        .attr('width', width)                        .attr('height', height);   var xscale = d3.scalelinear().domain([-1,1]).range([0+margin.left, width-margin.right]);  var yscale = d3.scalelinear().domain([-1,1]).range([height - margin.bottom, 0 + margin.top]);   // add x axis  svg.append("g")      .attr("transform", "translate(0," + (height - margin.top) + ")")      .attr("class", "axis")    .call(d3.axisbottom(xscale)      .ticks(4)      .ticksizeouter(0)      );   svg.append("g")      .attr("transform", "translate(0," + (margin.top) + ")")      .attr("class", "axis")    .call(d3.axistop(xscale)      .ticks(0)      .ticksizeouter(0)      );   // add y axis  svg.append("g")      .attr("transform", "translate(" + (margin.left)  + ", 0)")      .attr("class", "axis")    .call(d3.axisleft(yscale)      .ticks(4)      .ticksizeouter(0)      );   svg.append("g")      .attr("transform", "translate(" + (width - margin.right)  + ", 0)")      .attr("class", "axis")    .call(d3.axisright(yscale)      .ticks(0)      .ticksizeouter(0)      );  //grid lines svg.append('line')    .attr('x1', xscale(0))    .attr('y1', height - margin.bottom)    .attr('x2', xscale(0))    .attr('y2', margin.top)     .style('stroke', 'grey')    .style('stroke-width', 1);  //grid lines svg.append('line')    .attr('x1', margin.left)    .attr('y1', yscale(0))    .attr('x2', width - margin.right)    .attr('y2', yscale(0))     .style('stroke', 'grey')    .style('stroke-width', 1);   </script> 

and here's result

enter image description here

i ran same problem recently. below solution, have feeling there may more elegant way this. if take @ x1 , x2 components of axis tick see both have value of 0.5. web inspector output

if offset line x1 , x2 values 0.5, line correctly:

//grid lines svg.append('line') .attr('x1', xscale(0) + 0.5) .attr('y1', height - margin.bottom) .attr('x2', xscale(0) + 0.5) .attr('y2', margin.top) .style('stroke', 'grey') .style('stroke-width', 1); 

here full code: js fiddle gridlines


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -