D3轴刻度和网格线不对齐

时间:2016-11-10 07:40:46

标签: d3.js svg

我想制作一个只有一条垂直和一条横跨(0,0)点的水平网格线的图。我有以下脚本,但不幸的是轴刻度和网格线的原点没有正确对齐。这种差异的根源是什么?如何解决这个问题?

<!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>

这是结果

enter image description here

1 个答案:

答案 0 :(得分:2)

我最近遇到了同样的问题。下面是一个解决方案,但我觉得可能有更优雅的方式来做到这一点。如果你看一下轴刻度的x1和x2分量,你会发现它们的值都是0.5。 web inspector output

如果您将x1和x2行的值偏移0.5,它将正确排列:

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

以下是完整代码:js fiddle with gridlines

相关问题