简体   繁体   中英

time x axis in d3 js

Here, x-axis is the time axis, with following code I see x-axis little bit displaced on right side. Any idea why does it happen? And how can we fix it?

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

Here is an example fiddle of the problem.

What's happening is the Date object is taking the date and adjusting it based on your local time. This is actually what is causing the offset, since the real dates will slightly vary. An easy way to fix that is to use interval.utc , so it will take times intervals in UTC rather than local time. So for var x_axis rather than having:

.ticks(d3.time.days,1)

Replace it with:

.ticks(d3.time.days.utc,1)

Fiddle Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM