2016-11-10 9 views
1

(0,0)点を横切る1本の垂直グリッド線と1本の水平グリッド線を持つプロットを作成したいとします。私は次のスクリプトを持っていますが、残念ながら軸の目盛りとグリッド線の起点が正しく整列していません。この不一致の原因は何ですか?これをどのように修正できますか?D3の軸目盛りとグリッド線が一致しない

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

答えて

2

です。以下は解決策ですが、私はこれを行うよりエレガントな方法があるかもしれないと感じています。軸目盛りのx1とx2のコンポーネントを見ると、両方とも0.5の値が表示されます。 web inspector output

あなたが0.5で、あなたのラインx1とx2の値をオフセットした場合、それが正しく並んでますが:ここでは

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

+0

私は0.5シフト幅を相殺することだと思います行の –

関連する問題