D3 axis ticks and grid lines do not align

1,046 views
Skip to first unread message

Spyros Theodoridis

unread,
Nov 10, 2016, 2:48:58 AM11/10/16
to d3-js
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:


Bernhard Freiberger

unread,
Nov 18, 2016, 11:50:59 AM11/18/16
to d3-js
Hi Spyros!

I noticed the same behavior - Apparently axes components are shifted 0.5 pixel to the right and downwards by D3, resulting in the non-alignment. Have you found a solution meanwhile?

You can also check out my posting in this group where I describe the subject:
https://groups.google.com/forum/#!topic/d3-js/-Sw0Wdnkeko

Best Regards,

Bernhard

Spyros Theodoridis

unread,
Nov 18, 2016, 11:57:08 AM11/18/16
to d3-js
Hi Bernhard,

I ended up using Mike's solution here:

https://github.com/d3/d3-axis/commit/ced588cbf6bfd7c275a8e8389e490e340ae75ad7

Cheers,
Spyros
Reply all
Reply to author
Forward
0 new messages