简体   繁体   中英

D3.js Time scale starting at now

I have a graph which shows live data over the past 90 minutes currently my x axis is labelled 90 to 0 using

xRRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right])
                           .domain([90,0])

What I want to do is replace the numbers 0 - 90 with times, ie the 90 would be now-90 and the 0 would be now I have tried the following but it fails to draw the axis, any ideas where I have went wrong

var xStart = Math.round(+new Date()/1000);
var xEnd = xStart - (60*90);
xTRange = d3.scale.time().range([MARGINS.left, WIDTH - MARGINS.right])
                         .domain([xEnd, xStart])
                         .nice() 
xTAxis = d3.svg.axis().scale(xTRange)
                      .tickSize(20)
                      .tickSubdivide(true);
vis.append('svg:g').attr('class', 'x axis')
                   .attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')')
                   .call(xTAxis);

You seem to have swapped the xEnd and xStart. In your first code block, the smaller value is at the end. In your 2nd, the larger values is at the end.

Also, your first line converts the xStart and xEnd values into seconds. You don't convert them back to milliseconds in your domain call. When d3 coerces them into dates, they won't be what you expect (will be far lesser)

As @potatopeelings excellent answer states, JavaScript works with milliseconds. Also, a couple of other things. It's d3.time.scale , not d3.scale.time . And in your scale assignment, you need to reverse your xEnd and xStart .

Here it all is working:

 <!DOCTYPE html> <html> <head> <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> </head> <body> <script> var vis = d3.select('body') .append('svg') .attr('width', 400) .attr('height', 150); var xStart = new Date(); var xEnd = xStart - (90 * 60000); // 60,000 milliseconds in minute xTRange = d3.time.scale() .range([20, 380]) .domain([xStart, xEnd]) .nice(); xTAxis = d3.svg.axis().scale(xTRange) .tickSize(20) .tickSubdivide(true); vis.append('svg:g').attr('class', 'x axis') .attr('transform', 'translate(0,' + 10 + ')') .call(xTAxis); </script> </body> </html> 

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