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>
和這裏的結果
我覺得0.5轉變爲以抵消寬度的線。 –