spyrostheodoridis
spyrostheodoridis

Reputation: 518

D3 axis ticks and grid lines do not align

I would like to make a plot with only one vertical and one horizontal grid line that cross the (0,0) point. I have the following script but unfortunately the axis ticks and the origins of the grid lines do not align properly. What is the source of this discrepancy and how can I 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 the 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 the 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 the result

enter image description here

Upvotes: 1

Views: 1388

Answers (1)

Chris
Chris

Reputation: 66

I ran into the same problem recently. Below is a solution, but I have a feeling there may be a more elegant way to do this. If you take a look at the x1 and x2 components of the axis tick you will see they both have a value of 0.5. web inspector output

If you offset your line x1 and x2 values by 0.5, it will line up 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 is the full code: js fiddle with gridlines

Upvotes: 3

Related Questions