2016-11-10 104 views
1

我想繪製只有一條垂直網格線和一條橫跨(0,0)點的水平網格線的繪圖。我有以下的腳本,但不幸的是軸的滴答聲和網格線的起源沒有正確對齊。這種差異的根源是什麼?我該如何解決這個問題?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轉變爲以抵消寬度的線。 –