如何在xAxis上使用d3.js格式化时间
根据演示http://bl.ocks.org/mbostock/3883245
我不知道如何在xAxis上格式化时间
这是我的代码:js:
var data = [{
“creat_time”:“2013-03-12 15:09:04”,
“record_status”:“ok”,
“roundTripTime”:“16”
},{
“creat_time”:“2013-03-12 14:59:06”,
“record_status”:“ok”,
“roundTripTime”:“0”
},{
“creat_time”:“2013-03-12 14:49:04”,
“record_status”:“ok”,
“roundTripTime”:“297”
},{
“creat_time”:“2013-03-12 14:39:06”,
“record_status”:“ok”,
“roundTripTime”:“31”
},{
“creat_time”:“2013-03-12 14:29:03”,
“record_status”:“ok”,
“roundTripTime”:“0”
}];
var margin = {top:20,right:20,bottom:30,left:50};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format(“%Y-%m-%d%H:%M:%S”)。parse;
var x = d3.time.scale()
.range([0,width]);
var y = d3.scale.linear()
.range([height,0]);
var xAxis = d3.svg.axis()
.scale(x)的
。东方( “底部”);
var yAxis = d3.svg.axis()
.scale(y)的
。东方( “左”);
var line = d3.svg.line()
.x(function(d){return x(d.creat_time);})
.y(function(d){return y(d.roundTripTime);});
var svg = d3.select(“body”)。append(“svg”)
.attr(“width”,width + margin.left + margin.right)
.attr(“height”,height + margin.top + margin.bottom)
.append( “G”)
.attr(“transform”,“translate(”+ margin.left +“,”+ margin.top +“)”);
data.forEach(function(d){
d.creat_time = parseDate(d.creat_time);
d.roundTripTime = + d.roundTripTime;
});
x.domain(d3.extent(data,function(d){return d.creat_time;}));
y.domain(d3.extent(data,function(d){return d.roundTripTime;}));
svg.append( “G”)
.attr(“class”,“x axis”)
.attr(“transform”,“translate(0,”+ height +“)”)
.CALL(x-轴);
svg.append( “G”)
.attr(“class”,“y axis”)
.CALL(Y轴)
.append( “文本”)
.attr(“transform”,“rotate(-90)”)
.attr(“y”,6)
.attr(“dy”,“.71em”)
.style(“text-anchor”,“end”)
.text(“return time(ms)”);
svg.append( “path”)
.datum(数据)
.attr(“class”,“line”)
.attr(“d”,line);
这是svg: 
在svg中,时间是12小时,但在我的数据时间是24小时。 如何保持svg和数据相同的格式?
任何帮助表示赞赏。 (ps:我希望你不介意我的英语,这太糟糕了。)
您可以在轴对象上使用tickFormat函数,如下所示
var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .tickFormat(d3.time.format("%H"));
%H指定hour (24-hour clock) as a decimal number [00,23] 。 检查此链接D3时间格式以获取更多信息
你可以在这个支stream24小时的例子中看看一个可行的例子
接受的答案确实是正确的,但在我的情况下,我需要灵活的格式来适应不同的尺度(思考缩放),而且还要确保使用24小时的时钟。 关键是定义一个多分辨率的时间格式 。 详细信息请参阅文档页面。
我的代码:
var axisTimeFormat = d3.time.format.multi([ [".%L", function(d) { return d.getMilliseconds(); }], [":%S", function(d) { return d.getSeconds(); }], ["%H:%M", function(d) { return d.getMinutes(); }], ["%H:%M", function(d) { return d.getHours(); }], ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], ["%b %d", function(d) { return d.getDate() != 1; }], ["%B", function(d) { return d.getMonth(); }], ["%Y", function() { return true; }] ]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .tickFormat(axisTimeFormat);
我想将这个链接添加到一个真棒演示页面。 这是一个操场,当你可以select什么格式说明你需要你的情况。 当你不记得/知道你应该传给你的d3.timeFormat函数的格式说明符时,这是非常有用的。
我也想注意,如果你有d3版本4,你应该使用d3.timeFormat函数,而不是d3.time.format 。