gpt4 book ai didi

d3.js - 如何在 nvd3/d3.js 的 x 轴上显示日期?

转载 作者:行者123 更新时间:2023-12-03 06:04:52 26 4
gpt4 key购买 nike

我正在使用 nvd3,但我认为这是关于时间尺度和格式的一般 d3.js 问题。我创建了一个简单的示例来说明问题(请参阅下面的代码):

如果我省略 xAxis 的 .tickFormat,则无需日期格式即可正常工作。通过下面的示例,我收到错误:

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'
}
];
}

示例(现已修复)位于 nvd3 with date axis

最佳答案

尝试在 x 轴的刻度传递给格式化程序之前创建一个新的 Date 对象:

.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })

请参阅 d3.time.format 的文档了解如何自定义格式化字符串。

关于d3.js - 如何在 nvd3/d3.js 的 x 轴上显示日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com