how to use d3.time.scale to create label for each hour of day and each day of week

百般思念 提交于 2019-12-12 02:27:19

问题


Ok there may be so many duplicates to this question on SO, i have checked almost all of them but i couldn't figure out answer to my quest

I have this service which gives, count of hits to my site every minute and i want to display it in dashboard using d3 nvd3 line graph.

I got all working except one thing, i want the labels on x axsis to start from midnight to midnight

(00:00 to 23:00) and in intervals of 1hr [00:00, 01:00, 02:00, 03:00, 04:00, ......22:00, 23:00]

But i am not able to get this right i tried all possible combinations using d3.time.scale but i am not getting it right i get all random labels on x axis

this is the function i am currently using which give those random values

$scope.xAxisTickFormatFunction = function() {
        return function(d) {
            return d3.time.format("%H:%M")(new Date(d));
        };
    };

After i get this timeline of day working, i would like to do this for per day of week too.

i really can't figure out how d3.time.scale works , i have been working on this since yesterday

pls help

thanks a lot


回答1:


The real trick is to be able to take advantage of all the built-in time formatting/interval tools in D3. Here's a very simple example, based off this block, where you define your time scale across the entirety of one day (24 hours) using d3.time.scale().nice():

// Set up the SVG
var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height);

// Define your time scale
var x = d3.time.scale()
    .domain([new Date, new Date])
    .nice(d3.time.day)
    .range([0, width - 50]);

// Add your axis
svg.append("g")
   .attr("transform", "translate(5,0)")
   .call(d3.svg.axis().scale(x).ticks(24).tickFormat(d3.time.format("%H:%M")));

The above code produces this axis:



来源:https://stackoverflow.com/questions/26926876/how-to-use-d3-time-scale-to-create-label-for-each-hour-of-day-and-each-day-of-we

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!