I am trying to display a multi-line chart of temperatures for 5 days on an hourly basis. I was able to create the both axes but I'm having trouble displaying the lines.
I have a JSON like so where x is a date object for every 3 hours and y is the temperature.
var dataset = [
//day 1
[
{x: Date 2015-09-07T21:00:00.000Z, y: 30.75},
{x: Date 2015-09-08T00:00:00.000Z, y: 29.32},
{x: Date 2015-09-08T03:00:00.000Z, y: 25.67},
{x: Date 2015-09-08T06:00:00.000Z, y: 22.7}
],
//day 2
[
{x: Date 2015-09-08T09:00:00.000Z, y: 23.69},
{x: Date 2015-09-08T12:00:00.000Z, y: 24.18},
{x: Date 2015-09-08T15:00:00.000Z, y: 26.69},
{x: Date 2015-09-08T18:00:00.000Z, y: 22.36},
{x: Date 2015-09-08T21:00:00.000Z, y: 23.91},
{x: Date 2015-09-09T00:00:00.000Z, y: 22.98}
],
//day 3
Array[8],
//day 4
Array[8],
//day 5
Array[8]
]
When initialize the graph like below, instead of a multi-line graph, I get one line containing all 4 days.
var chart = lineChart("graph")
.x(d3.time.scale().domain([
dataset[0][0].x, dataset[3][7].x
]))
.y(d3.scale.linear().domain([min, max]));
dataset.forEach(function (series) {
chart.addSeries(series);
});
chart.render();
If I change the domain to,
dataset[4][0].x, dataset[4][7].x
it only draws the line for that day.
The strange thing is that when I "Inspect Elemet" via the browser, I can see that all 5 paths have been drawn out but they just dont show up on the UI. I think this has something to do with the way I'm setting the domain but I'm not sure what.
How do I set the domain so that d3js plots each days array on a 24-hour x-axis?
If I understand correctly, you want to have the x-axis from midnight to midnight, as if everything is happening "on one day", like so:
NOTE: something is a bit weird with the timestamps in the source. I have no idea how dt and dt_text are related. Please adjust my examples accordingly...
How can you get that?
The problem in your code is indeed related to the domain. How?
If you set the domain to be from the very first timestamp to the last, like:
.domain([
dataset[0][0].x, dataset[3][7].x
])
then the chart will span over 4 days (by the way: these hard-coded indices are not very robust coding...)
So the chart will then obviously plot over all days, it has no way of knowing that you only want hourly time-stamps.
If you, on the other hand, just use the most recent day as domain:
.domain([
dataset[3][0].x, dataset[3][7].x
]))
It will plot just that, i.e. the last day. The other lines will be plotted too (what you see in the inspector), but the will be hidden away on the left (as you clip the stuff).
So: the problem is, that the x-coordinates are different, as they occur on different dates. There is plenty of ways to work around that (I personally always use moment.js for dates), but to show the effect, here's a quick hack to achieve the graph above:
-> JSFiddle
What did I do? I added a new helper function to calculate the x time-stamp:
function gDate2(date) {
var now = new Date();
var hours = (new Date(date * 1000)).getHours();
var date = now.getDate();
var month = now.getMonth();
var d = new Date(2015, month, date, hours, 0, 0, 0);
return d;
}
Yes, it's not pretty. Personally, I like moment.js to calculate dates and stuff. The important part is that I return all dates as if it's all today (or any other arbitrary day). Then I extract the hour of the timestamp of the according data point and add that (as in the note: maybe you need minutes, seconds too?)
If you are going to use it, please make sure you have timezones, day-light saving etc. under control! I hate dates...)
And again: I am not sure about dt and dt_text. Make sure you got that right!
I hope this helps.
Related
I am building a timeline chart - that will change its date scale at the top when the brush becomes small to the scope of 1 day -- but when it hits this mode -- the labels overlap and it looks messy until you get to a 12 hour spread.
What is the best way of cleaning this functionality up so it doesn't overlap. I thought about having 1 line that shows date -- and another line under it that shows the hours at that level.
https://jsfiddle.net/aLh9d51t/
var tFormat = '%Y-%m';
var tTick = 'timeMonth';
if (days < 40) {
tFormat = '%Y-%m-%d';
tTick = 'timeWeek';
}
if (days <= 7) {
tFormat = '%Y-%m-%d';
tTick = 'timeDay';
}
if (days <= 1) {
tFormat = '%Y-%m-%d %H%p';
tTick = 'timeHour';
}
First, you can hide redundant parts of date when possible: show years, months, days only if there are more than one visible. So you definitely do not need years and months when you show hours and minutes.
Just look how default d3 axis handles this (e.g. https://bl.ocks.org/mbostock/1166403).
Second, considering your chart has fixed width, you can fine-tune different formats for different zoom levels (you already do this in your code snippet).
Take a look at this example: http://bl.ocks.org/oluckyman/6199145
It has similar logic as in your code snippet:
https://gist.github.com/oluckyman/6199145#file-axisdaysview-js-L33-L58
But the decision which format to choose depends on chart width:
https://gist.github.com/oluckyman/6199145#file-axisdaysview-js-L72-L75
And third, if you restricted to long labels for some reason, you can rotate them to 30°-45°
Also this could be useful: https://bl.ocks.org/mbostock/4149176
Summary
I have a large collection of data with various datetimes. Currently I have been able to group all my data to display properly in a local timezone; however, when trying to display this data in a different timezone the lines on a lineChart get choppy and the connection between them is not as smooth as when in a local timezone.
I had found this link here detailing a possible solution, but sadly this won't work without me duplicating my entire dataset with times offset from utc and then once as normal. The data I have is not only used in several charts to gain insights about trends and statistics, but there is a raw table used for display/editing/reviewing specific data members. Thus translating one into a utc time and calculating the time change in utc time would throw the other off.
https://groups.google.com/forum/#!msg/d3-js/iWmP9Npv2Go/xyypdLjWu2QJ
My question is: Is there a way to translate datetime data across timezones and have dc.js respect the timezone you would like to display in. I would like the adjusted graphs to look the same way the local graph looks where the lines are not one-sided based on the timezone.
code and photos
fiddle: https://jsfiddle.net/spacarar/j0urt9sy/49/
this is the correctly displaying image for my local timezone. The lines are smooth transitions between dates.
This is the incorrectly displaying image for any other timezone (depending on which side of my local changes orientation from leaning left to leaning right)
A simplified version of my data looks something like this:
var data = [
{
value: 42,
datetime: '2019-10-24T07:18:00.000000'
},
{
value: 10,
datetime: '2019-10-24T07:19:12.000000'
},
{
value: 12,
datetime: '2019-10-29T04:18:00.000000'
},
{
value: 8,
datetime: '2019-10-29T09:18:00.000000'
}
]
which I then fake group to fill in any dates that may not be present in the data and translate them using moment-timezone to end up with a data structure similar to this
{
value: 0,
datetime: moment timezone object with full datetime,
date: moment timezone object representing only date (0 hours, minutes, seconds, ms)
}
this fake grouped/fixed data is then used to create the chart with the following code
var ndx = dc.crossfilter(fakeGroupedData)
var dateDim = ndx.dimension(dc.pluck('date'))
var top = dateDim.top(1)[0] ? dateDim.top(1)[0].date : null
var bottom = dateDim.bottom(1)[0] ? dateDim.bottom(1)[0].date : null
var chart = dc.lineChart('#date-chart')
chart.yAxis().tickFormat(dc.d3.format(',.0f'))
chart.xAxis().ticks(10).tickFormat(d => moment(d).format('M/D'))
chart.dimension(dateDim)
.group(dateDim.group().reduceSum(dc.pluck('value')))
.x(dc.d3.scaleTime().domain([bottom, top]).nice())
.elasticY(true)
.renderArea(true)
.render()
A couple of points about your date-filling.
This is not what's normally meant by a "fake group". You're filling in the source data and all of your crossfilter groups are completely "real" :)
There isn't any point in filling at a higher resolution than you intend to show. To simplify the problem, I changed your code to fill by days, and it worked exactly the same:
let start = moment.tz(startDate, tzSelection).startOf('day')
let end = moment.tz(endDate, tzSelection).endOf('day')
let hours = end.diff(start, 'days')
for (let i = 0; i < hours; i++) {
let fakeTime = moment(start).add(i, 'days')
let date = moment(fakeTime.format('YYYY-MM-DD'))
fakeGroupedData.push({
value: 0,
datetime: fakeTime,
date
})
}
It might be easier to use d3-time, since that integrates tighter with dc.js, but I didn't want to make big changes to your code.
However, you are essentially quantizing by day, so you can set up your dimension to quantize to the beginning of the day in the current timezone, and that will fix your chart:
var dateDim = ndx.dimension(d => d3.timeDay(dc.pluck('date')(d)))
If you do this, you don't need to modify your input dates:
el.date = el.datetime //.clone().startOf('day')
D3 will truncate to the current day, and then crossfilter will bin at that resolution.
https://jsfiddle.net/gordonwoodhull/Lxvcoq3h/19/
Note that it's binning both of the 10/29 entries into one.
In my timezone UTC-5, the moment startOf('day') rounding was causing the first of those entries to land on the 28th, which matches what you said you wanted:
https://jsfiddle.net/gordonwoodhull/Lxvcoq3h/21/
You'll have to decide which one is correct for your application. The main point is that if you're displaying your charts in the local timezone, the data should be quantized to local days.
Good Evening Everyone,
I'm trying to take the data from a database full of hour reports (name, timestamp, hours worked, etc.) and create a plot using dc.js to visualize the data. I would like the timestamp to be on the x-axis, the sum of hours for the particular timestamp on the y-axis, and a new bar graph for each unique name all on the same chart.
It appears based on my objectives that using crossfilter.js the timestamp should be my 'dimension' and then the sum of hours should be my 'group'.
Question 1, how would I then use the dimension and group to further split the data based on the person's name and then create a bar graph to add to my composite graph? I would like for the crossfilter.js functionality to remain intact so that if I add a date range tool or some other user controllable filter, everything updates accordingly.
Question 2, my timestamps are in MySQL datetime format: YYYY-mm-dd HH:MM:SS so how would I go about dropping precision? For instance, if I want to combine all entries from the same day into one entry (day precision) or combine all entries in one month into a single entry (month precision).
Thanks in advance!
---- Added on 2017/01/28 16:06
To further clarify, I'm referencing the Crossfilter & DC APIs alongside the DC NASDAQ and Composite examples. The Composite example has shown me how to place multiple line/bar charts on a single graph. On the composite chart I've created, each of the bar charts I've added a dimension based off of the timestamps in the data-set. Now I'm trying to figure out how to define the groups for each. I want each bar chart to represent the total time worked per timestamp.
For example, I have five people in my database, so I want there to be five bar charts within the single composite chart. Today all five submitted reports saying they worked 8 hours, so now all five bar charts should show a mark at 01/28/2017 on the x-axis and 8 hours on the y-axis.
var parseDate = d3.time.format('%Y-%m-%d %H:%M:%S').parse;
data.forEach(function(d) {
d.timestamp = parseDate(d.timestamp);
});
var ndx = crossfilter(data);
var writtenDimension = ndx.dimension(function(d) {
return d.timestamp;
});
var hoursSumGroup = writtenDimension.group().reduceSum(function(d) {
return d.time_total;
});
var minDate = parseDate('2017-01-01 00:00:00');
var maxDate = parseDate('2017-01-31 23:59:59');
var mybarChart = dc.compositeChart("#my_chart");
mybarChart
.width(window.innerWidth)
.height(480)
.x(d3.time.scale().domain([minDate,maxDate]))
.brushOn(false)
.clipPadding(10)
.yAxisLabel("This is the Y Axis!")
.compose([
dc.barChart(mybarChart)
.dimension(writtenDimension)
.colors('red')
.group(hoursSumGroup, "Top Line")
]);
So based on what I have right now and the example I've provided, in the compose section I should have 5 charts because there are 5 people (obviously this needs to be dynamic in the end) and each of those charts should only show the timestamp: total_time data for that person.
At this point I don't know how to further breakup the group hoursSumGroup based on each person and this is where my Question #1 comes in and I need help figuring out.
Question #2 above is that I want to make sure that the code is both dynamic (more people can be handled without code change), when minDate and maxDate are later tied to user input fields, the charts update automatically (I assume through adjusting the dimension variable in some way), and if I add a names filter that if I unselect names that the chart will update by removing the data for that person.
A Question #3 that I'm now realizing I'll want to figure out is how to get the person's name to show up in the pointer tooltip (the title) along with timestamp and total_time values.
There are a number of ways to go about this, but I think the easiest thing to do is to create a custom reduction which reduces each person into a sub-bin.
First off, addressing question #2, you'll want to set up your dimension based on the time interval you're interested in. For instance, if you're looking at days:
var writtenDimension = ndx.dimension(function(d) {
return d3.time.hour(d.timestamp);
});
chart.xUnits(d3.time.hours);
This will cause each timestamp to be rounded down to the nearest hour, and tell the chart to calculate the bar width accordingly.
Next, here's a custom reduction (from the FAQ) which will create an object for each reduced value, with values for each person's name:
var hoursSumGroup = writtenDimension.group().reduce(
function(p, v) { // add
p[v.name] = (p[v.name] || 0) + d.time_total;
return p;
},
function(p, v) { // remove
p[v.name] -= d.time_total;
return p;
},
function() { // init
return {};
});
I did not go with the series example I mentioned in the comments, because I think composite keys can be difficult to deal with. That's another option, and I'll expand my answer if that's necessary.
Next, we can feed the composite line charts with value accessors that can fetch the value by name.
Assume we have an array names.
compositeChart.shareTitle(false);
compositeChart.compose(
names.map(function(name) {
return dc.lineChart(compositeChart)
.dimension(writtenDimension)
.colors('red')
.group(hoursSumGroup)
.valueAccessor(function(kv) {
return kv.value[name];
})
.title(function(kv) {
return name + ' ' + kv.key + ': ' + kv.value;
});
}));
Again, it wouldn't make sense to use bar charts here, because they would obscure each other.
If you filter a name elsewhere, it will cause the line for the name to drop to zero. Having the line disappear entirely would probably not be so simple.
The above shareTitle(false) ensures that the child charts will draw their own titles; the title functions just add the current name to those titles (which would usually just be key:value).
Here is my data about mac address. It is recorded per minute. For each minute, I have many unique Mac addresses.
mac_add,created_time
18:59:36:12:23:33,2016-12-07 00:00:00.000
1c:e1:92:34:d7:46,2016-12-07 00:00:00.000
2c:f0:ee:86:bd:51,2016-12-07 00:00:00.000
5c:cf:7f:d3:2e:ce,2016-12-07 00:00:00.000
...
18:59:36:12:23:33,2016-12-07 00:01:00.000
1c:cd:e5:1e:99:78,2016-12-07 00:01:00.000
1c:e1:92:34:d7:46,2016-12-07 00:01:00.000
5c:cf:7f:22:01:df,2016-12-07 00:01:00.000
5c:cf:7f:d3:2e:ce,2016-12-07 00:01:00.000
...
I would like to create 2 bar charts using dc.js and crossfilter. Please refer to the image for the charts.
The first bar chart is easy enough to create. It is brushable. I created the "created_time" dimension, and created a group and reduceCount by "mac_add", such as below:
var moveTime = ndx.dimension(function (d) {
return d.dd; //# this is the created_time
});
var timeGroup = moveTime.group().reduceCount(function (d) {
return d.mac_add;
});
var visitorChart = dc.barChart('#visitor-no-bar');
visitorChart.width(990)
.height(350)
.margins({ top: 0, right: 50, bottom: 20, left: 40 })
.dimension(moveTime)
.group(timeGroup)
.centerBar(true)
.gap(1)
.elasticY(true)
.x(d3.time.scale().domain([new Date(2016, 11, 7), new Date(2016, 11, 13)]))
.round(d3.time.minute.round)
.xUnits(d3.time.minute);
visitorChart.render();
The problem is on the second bar chart. The idea is that, one row of the data equals 1 minute, so I can aggregate and sum all minutes of each mac address to get the time length of each mac addresses, by creating another dimension by "mac_add" and do reduceCount on "mac_add" to get the time length. Then the goal is to group the time length by 30 minutes. So we can get how many mac address that have time length of 30 min and less, how many mac_add that have time length between 30 min and 1 hour, how many mac_add that have time length between 1 hour and 1.5 hour, etc...
Please correct me if I am wrong. Logically, I was thinking the dimension of the second bar chart should be the group of time length (such as <30, <1hr, < 1.5hr, etc). But the time length group themselves are not fix. It depends on the brush selection of the first chart. Maybe it only contains 30 min, maybe it only contains 1.5 hours, maybe it contains 1.5 hours and 2 hours, etc...
So I am really confused what parameters to put into the second bar chart. And method to get the required parameters (how to group a grouped data). Please help me to explain the solution.
Regards,
Marvin
I think we've called this a "double grouping" in the past, but I can't find the previous questions.
Setting up the groups
I'd start with a regular crossfilter group for the mac addresses, and then produce a fake group to aggregate by count of minutes.
var minutesPerMacDim = ndx.dimension(function(d) { return d.mac_add; }),
minutesPerMapGroup = minutesPerMacDim.group();
function bin_keys_by_value(group, bin_value) {
var _bins;
return {
all: function() {
var bins = {};
group.all().forEach(function(kv) {
var valk = bin_value(kv.value);
bins[valk] = bins[valk] || [];
bins[valk].push(kv.key);
});
_bins = bins;
// note: Object.keys returning numerical order here might not
// work everywhere, but I couldn't find a browser where it didn't
return Object.keys(bins).map(function(bin) {
return {key: bin, value: bins[bin].length};
})
},
bins: function() {
return _bins;
}
};
}
function bin_30_mins = function(v) {
return 30 * Math.ceil(v/30);
}
var macsPerMinuteCount = bin_keys_by_value(minutesPerMacGroup);
This will retain the mac addresses for each time bin, which we'll need for filtering later. It's uncommon to add a non-standard method bins to a fake group, but I can't think of an efficient way to retain that information, given that the filtering interface will only give us access to the keys.
Since the function takes a binning function, we could even use a threshold scale if we wanted more complicated bins than just rounding up to the nearest 30 minutes. A quantize scale is a more general way to do the rounding shown above.
Setting up the chart
Using this data to drive a chart is simple: we can use the dimension and fake group as usual.
chart
.dimension(minutesPerMacDim)
.group(macsPerMinuteCount)
Setting up the chart so that it can filter is a bit more complicated:
chart.filterHandler(function(dimension, filters) {
if(filters.length === 0)
dimension.filter(null);
else {
var bins = chart.group().bins(); // retrieve cached bins
var macs = filters.map(function(key) { return bins[key]; })
macs = Array.prototype.concat.apply([], macs);
var macset = d3.set(macs);
dimension.filterFunction(function(key) {
return macset.has(key);
})
}
})
Recall that we're using a dimension which is keyed on mac addresses; this is good because we want to filter on mac addresses. But the chart is receiving minute-counts for its keys, and the filters will contain those keys, like 30, 60, 90, etc. So we need to supply a filterHandler which takes minute-count keys and filters the dimension based on those.
Note 1: This is all untested, so if it doesn't work, please post an example as a fiddle or bl.ock - there are fiddles and blocks you can fork to get started on the main page.
Note 2: Strictly speaking, this is not measuring the length of connections: it's counting the total number of minutes connected. Not sure if this matters to you. If a user disconnects and then reconnects within the timeframe, the two sessions will be counted as one. I think you'd have to preprocess to get duration.
EDIT: Based on your fiddle (thank you!) the code above does seem to work. It's just a matter of setting up the x scale and xUnits properly.
chart2
.x(d3.scale.linear().domain([60,1440]))
.xUnits(function(start, end) {
return (end-start)/30;
})
A linear scale will do just fine here - I wouldn't try to quantize that scale, since the 30-minute divisions are already set up. We do need to set the xUnits so that dc.js knows how wide to make the bars.
I'm not sure why elasticX didn't work here, but the <30 bin completely dwarfed everything else, so I thought it was best to leave that out.
Fork of your fiddle: https://jsfiddle.net/gordonwoodhull/2a8ow1ay/2/
I'm working with a D3 time scale. My input data is in seconds, and it's duration data rather than dates - so 10 seconds, 30 seconds etc.
I want to create an axis that lets me do the following:
Display ticks formatted in minutes and seconds: like "0m 30s", "1m 00s", etc. This formatting on its own is fairly straightforward, but not when I also need to...
Display ticks at intervals that look neat when formatted in minutes. If I just use D3's default tick formatting then I get ticks at intervals that make sense in minutes, but not seconds.
Here is my code:
var values = [100,200,300....]; // values in seconds
var formatCount = d3.format(",.0f"),
formatTime = d3.time.format("%Mm %Ss"),
formatMinutes = function(d) {
var t = new Date(2012, 0, 1, 0, 0, d);
t.setSeconds(t.getSeconds() + d);
return formatTime(t);
};
var x = d3.scale.linear()
.domain([0, d3.max(values)])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatMinutes);
This gives me nicely-formatted ticks at irregular intervals: "16m 40s", "33m 20s" etc. How can I generate ticks at "10m 00s", "20m 00s", etc?
The obvious answer would be to transform the values array into minutes, use a linear scale and write a formatter to handle it, but I'd prefer to use a time scale if possible
Here is a JSFiddle to demonstrate the problem: http://jsfiddle.net/83Xmf/
Normally when making a time scale, you would use d3.time.scale(), rather than a linear scale.
Your case is a little odd in that you are using abstract durations of time, and not specific points in time for your data. Unfortunately it seems that d3's built in time functionality is not well-suited to this case. There are a couple of options I can think of for workarounds:
Option 1: Use a linear scale with manual .tickValues()
Rather than formatting your ticks using a Date object. You could simply break down your data value (which is in seconds) into hours, minutes, and seconds. Something like this:
formatMinutes = function(d) {
var hours = Math.floor(d / 3600),
minutes = Math.floor((d - (hours * 3600)) / 60),
seconds = d - (minutes * 60);
var output = seconds + 's';
if (minutes) {
output = minutes + 'm ' + output;
}
if (hours) {
output = hours + 'h ' + output;
}
return output;
};
Basically, this takes the total number of seconds, creates an hour for every 3600 seconds, creates a minute for each remaining 60 seconds, and finally gives back the remaining seconds. Then it outputs a string representation, for example: 17s or 12m 42s or 4h 8m 22s.
Then when you make your axis, you can use the .tickValues() method to assign a range from zero to your data's max value, going by steps of 600, since there are 600 seconds in 10 minutes. That would look like this:
var x = d3.scale.linear()
.domain([0, d3.max(values)])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatMinutes)
.tickValues(d3.range(0, d3.max(values), 600));
Here's a JSFiddle of the output.
Option 2: Use a time scale with a fixed duration for .ticks()
Time scales let you specify directly that you'd like ticks every 10 minutes. You do that simply by passing a d3 duration and a multiplier to the .ticks() method of your axis. Like this:
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.minute, 10)
In order to do this, you must first set up your time scale. For the domain of your scale, you can use a range of millisecond values, since d3 will turn these into Date objects. In this case, since your data is in seconds, we can simply multiply by 1000 to get milliseconds. In this case we'll round up the max value to the nearest millisecond, since it must be an integer to make a valid date:
var x = d3.time.scale()
.domain([0, Math.ceil(d3.max(values) * 1000)])
.range([0, width]);
Finally, you can pass your format in directly to the axis, using .tickFormat():
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.minute, 10)
.tickFormat(d3.time.format('%Mm %Ss'));
However, at this point I need to point something out because, as I mentioned, the built-in time functions are not well-suited to dealing with abstract durations. I'm going to change the .tickFormat to show the hours as well:
.tickFormat(d3.time.format('%Hh %Mm %Ss'));
Have a look at the JSFiddle of what the result would be...
Depending on where you are in the world, you'll get a different value for the hours place. I'm on the East coast of the US, so my hours place says 19. Where is that coming from? Shouldn't it be zero?
Well, unfortunately, when we made the domain of the scale go from 0 to the number of milliseconds of the largest data value, it created regular Date objects, using those values for the millisecond input. This means that they represent the number of milliseconds since midnight UTC time on January 1, 1970. Here in the Eastern time zone of the US, that means it was 19:00:00 on December 31, 1969. That's where the 19 comes from, or whatever other value you get.
If you know that all of your data will be less than 1 hour, then perhaps you can just ignore this. If you need to use an hours place, you can work around this by forcing d3 to use UTC time to format the axis using d3.time.format.utc():
.tickFormat(d3.time.format.utc('%Hh %Mm %Ss'))
Here's the JSFiddle updated to use UTC.
Now you can see that the hour is 0 as expected.
Of course, if any of your data is ever longer than 24 hours, this method won't work at all, and you'll have to resort to doing the axis manually as in Option 1.
Hopefully this helps to at least get you started, it's a tricky problem though, and there doesn't seem to be an elegant solution built into the library for handling this. Perhaps it would make for a good feature request on d3's git repo. I'd love to hear if #mbostock has any suggestions on how to handle abstract durations of time in d3 without having to be tied to Date objects, which require references to absolute points in time.