Reputation: 119
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 an answer to my quest.
I have this service which gives a count of hits to my site every minute and I want to display it in a dashboard using a d3 nvd3 line graph.
I got it all working except one thing, I want the labels on the x axis to go from midnight to midnight, i.e (00:00 to 23:00)
in intervals of 1 hour [00:00, 01:00, 02:00, 03:00, 04:00, ..., 22:00, 23:00]
But I am not able to get this right. I have 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 gives those random values:
$scope.xAxisTickFormatFunction = function() {
return function(d) {
return d3.time.format("%H:%M")(new Date(d));
};
};
After I get this timeline of a day working, I would like to do this per each day of the week too.
I really can't figure out how d3.time.scale
works, I have been working on this since yesterday.
Upvotes: 0
Views: 5381
Reputation: 22922
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:
Upvotes: 3