这里,x轴是时间轴,下面的代码我看到x轴在右侧移位了一点点。知道为什么会这样吗?我们如何解决这个问题?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<script>
$(document).ready(function(){
var pad = 100;
var width = 700;
var height = 400;
var dateString=["2014-02-17","2014-02-18","2014-02-19","2014-02-20","2014-02-21"];
var value=[0,1000,2000,3000,4000];
var y_extent = d3.extent(value,function(v){return v});
var x_extent = d3.extent(dateString,function(ds){return new Date(ds)});
console.log(x_extent,y_extent);
var xScale = d3.time.scale()
.domain(x_extent)
.rangeRound([pad,width-(2*pad)]);
var yScale = d3.scale.linear()
.domain(y_extent)
.range([height-pad,0]);
var svg =d3.select(".draw")
.append("svg")
.attr("width",width)
.attr("height",height);
var x_axis = d3.svg.axis().scale(xScale).orient("bottom").ticks(d3.time.days,1).tickFormat(d3.time.format("%d %b"));
var y_axis = d3.svg.axis().scale(yScale).orient('left');
svg.append("g")
.attr("class","x axis")
.attr("transform","translate(0,"+(height-pad)+")")
.call(x_axis);
svg.append("g")
.attr("class","y axis")
.attr("transform","translate("+pad+",0)")
.call(y_axis);
for(var i=0;i<value.length;i++) {
svg.append("circle")
.attr("r", 5)
.attr("cx", xScale(new Date(dateString[i])))
.attr("cy",yScale(0))
.style("fill", "red");
}
});
</script>
</head>
<body>
<div class="draw">
</div>
</body>
</html>
答案 0 :(得分:0)
发生了什么Date
对象正在记录日期并根据您当地时间进行调整。这实际上是导致偏移的原因,因为实际日期会略有不同。解决这个问题的一种简单方法是使用interval.utc
,因此需要UTC时间而不是本地时间。所以var x_axis
而不是:{/ p>
.ticks(d3.time.days,1)
将其替换为:
.ticks(d3.time.days.utc,1)