如何在x轴上显示nvd3 / d3.js的日期? [英] How do I display dates on the x-axis for nvd3 / d3.js?
问题描述
我使用nvd3,但我认为这是一个一般的d3.js关于时间尺度和格式的问题。我创建了一个简单的例子来说明这个问题(见下面的代码):
如果我省略xTableFormat xAxis,它没有日期格式化。在下面的例子中,我得到错误:
未捕获TypeError:Object 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
}
/ ******** ******************************
*简单的测试数据生成器
* /
function fakeActivityByDate(){
var lineData = [];
var y = 0;
var start_date = new Date() - days(365); //一年前
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'
}
];
}
示例(现在固定)位于 nvd3 with date axis
。尝试在将x轴的刻度传递给格式器之前创建一个新的 Date
对象:
.tickFormat(function(d){return d3.time.format('%b%d')新的日期(d));})
请参阅 d3.time.format 查看如何自定义格式化字符串。 p>
I'm using nvd3, but I think this is a general d3.js question about time scale and formatting. I've created a simple example that illustrates the problem (see code below):
If I omit .tickFormat for the xAxis, it works fine without date formatting. With the example below I get the error:
Uncaught TypeError: Object 1326000000000 has no method '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'
}
];
}
The example (now fixed) is in nvd3 with date axis.
Try creating a new Date
object before the tick for the x-axis gets passed to the formatter:
.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })
See the documentation for d3.time.format to see how you can customize the formatting string.
这篇关于如何在x轴上显示nvd3 / d3.js的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!