使用d3.js在x轴上显示相对时间 [英] Displaying Relative Time on x-axis with d3.js
本文介绍了使用d3.js在x轴上显示相对时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用nvd3.js来显示随着时间的推移(近乎实时;数据每3分钟更新一次)。现在数据似乎正确显示,除了x轴显示的纪元时间不是很易读。如何让x轴显示x Minutes Ago而不是纪元时间?
I'm trying to use nvd3.js to display ratings over time (in near real time; the data updates every 3 minutes). Right now the data appears to be showing correctly except the x-axis displays epoch time which isn't very readable. How can I have the x-axis display "x Minutes Ago" rather than the epoch time?
这是我正在使用的代码:
Here is the code that I am using:
nv.addGraph(function() {
var chart = nv.models.lineChart();
chart.xAxis
.axisLabel('Time')
.tickFormat(d3.format('r'));
chart.yAxis
.axisLabel('Rating')
.tickFormat(d3.format('.2f'));
d3.select('#chart svg')
.datum(data())
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
function data() {
var data = [ { x: 1345457533, y: -0.0126262626263 },
{ x: 1345457409, y: 0.0224089635854 },
{ x: 1345457288, y: 0.0270935960591 },
{ x: 1345457168, y: -0.0378151260504 },
{ x: 1345457046, y: -0.115789473684 } ]
return [
{
values: data,
key: "Sample1",
color: "#232066"
}
];
}
推荐答案
使用自定义格式功能使用例如的标签 moment.js 。
Use a custom format function for the labels that uses e.g. moment.js. Something along the lines of
function myFormat(d) {
return moment(d * 1000).fromNow();
}
这篇关于使用d3.js在x轴上显示相对时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文