0
我有下面的代碼在d3的時間尺度上創建一個條形圖,但是最後一個條形總是離開軸線。我不確定是什麼問題以及如何解決這個問題,我已經花了幾個小時看着它。 我在做什麼錯? d3條形圖溢出
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var parseDate = d3.time.format("%Y-%m").parse;
var margin = {top: 20, right: 100, bottom: 20, left: 100},
outerWidth = 1000;
innerWidth = outerWidth - margin.left - margin.right; //800
outerHeight = 300;
innerHeight = outerHeight - margin.top - margin.bottom; //300
var xScale = d3.time.scale()
.range([0, innerWidth])
.nice(d3.time.week);
var yScale = d3.scale.linear()
.range([innerHeight,0]);
var mainContainer = d3.select("body").append("svg")
.attr("width", outerWidth)
.attr("height", outerHeight);
var mainGroup = mainContainer.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("bar-data.csv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
//xScale.domain([new Date(parseDate("2013-01")), new Date(parseDate("2017-12"))]);
xScale.domain(d3.extent(data, function(d) { return d.date; }));
yScale.domain([0, d3.max(data, function(d) { return d.value; })]);
mainGroup.append("g")
.attr("class", "x axis")
.attr('transform','translate(0,'+innerHeight+')')
.call(d3.svg.axis().scale(xScale).orient("bottom"));
mainGroup.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(yScale).orient("left"));
mainGroup.selectAll("bar")
.data(data)
.enter().append("rect")
.style("fill", "rgb(28, 175, 154)")
.attr("x", function(d) {return xScale(new Date(d.date));})
.attr("width", (innerWidth/data.length))
.attr("y", function(d) { return yScale(d.value); })
.attr("height", function(d) { return innerHeight - yScale(d.value); });
});
</script>
[D3基於時間尺度溢出軸]的可能重複(http://stackoverflow.com/questions/39811367/d3-time-based-scales-overflowing-axis) – Marcelo