我使用的是nvd3,但我认为这是一个关于时间尺度和格式的一般d3.js问题。我已经创建了一个简单的例子来说明这个问题(参见下面的代码):
如果我在xAxis中省略了.tickFormat,那么在不设置日期格式的情况下也能正常工作。在下面的例子中,我得到了错误:
未捕获TypeError:对象1326000000000没有方法“”getMonth“”
nv.addGraph(function() {
var chart = nv.models.lineChart();
chart.xAxis
.axisLabel('Date')
.rotateLabels(-45)
.tickFormat(d3.time.format('%b %d')) ;
chart.yAxis
.axisLabel('Activity')
.tickFormat(d3.format('d'));
d3.select('#chart svg')
.datum(fakeActivityByDate())
.transition().duration(500)
.call(chart);
nv.utils.windowResize(function() { d3.select('#chart svg').call(chart) });
return chart;
});
function days(num) {
return num*60*60*1000*24
}
/**************************************
* Simple test data generator
*/
function fakeActivityByDate() {
var lineData = [];
var y = 0;
var start_date = new Date() - days(365); // One year ago
for (var i = 0; i < 100; i++) {
lineData.push({x: new Date(start_date + days(i)), y: y});
y = y + Math.floor((Math.random()*10) - 3);
}
return [
{
values: lineData,
key: 'Activity',
color: '#ff7f0e'
}
];
}
该示例(现在已修复)是格式的。
发布于 2012-12-28 04:11:26
在x轴的记号传递给格式化程序之前,尝试创建一个新的Date
对象:
.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })
有关如何自定义格式字符串的信息,请参阅d3.time.format的文档。
发布于 2014-03-15 10:08:49
补充一下seliopou的答案,要正确地将日期与x轴对齐,请尝试以下操作:
chart.xAxis
.tickFormat(function(d) {
return d3.time.format('%d-%m-%y')(new Date(d))
});
chart.xScale(d3.time.scale()); //fixes misalignment of timescale with line graph
https://stackoverflow.com/questions/14058876
复制相似问题