【发布时间】:2016-01-27 22:02:49
【问题描述】:
我正在尝试使用 nvd3 在我的 Angular 应用程序中显示图表。我收到的日期格式为 2015-12-01T00:00:00。当我尝试将其格式化以在 x 轴上显示时,我总是收到带有 GMT 偏移量的 1970 年 1 月 1 日。下面是我的图表选项。 tickFormat 中传递的值是从哪里来的,或者我做错了什么。
vm.options = {
chart: {
type: 'historicalBarChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 65,
left: 50
},
x: function (d) {
return new Date(d.date).getTime();
},
y: function(d) {
return d.data;
},
showValues: true,
valueFormat: function(d){
return d3.format(',.1f')(d);
},
duration: 100,
xAxis: {
axisLabel: 'X Axis',
tickFormat: function(d) {
return d3.time.format('%b %y')(new Date(d));
},
rotateLabels: 30,
showMaxMin: false
},
yAxis: {
axisLabel: 'Y Axis',
axisLabelDistance: -10,
tickFormat: function(d){
return d3.format(',.1f')(d);
}
},
tooltip: {
keyFormatter: function(d) {
return d3.time.format('%x')(new Date(d));
}
},
zoom: {
enabled: true,
scaleExtent: [1, 10],
useFixedDomain: false,
useNiceScale: false,
horizontalOff: false,
verticalOff: true,
unzoomEventType: 'dblclick.zoom'
}
}
};
我的数据如下所示。
[
{
data: 4.3722
date: "2015-01-01T00:00:00"
},
{
data: 5.111
date: "2015-02-01T00:00:00"
},
{
data: 4.5758
date: "2015-03-01T00:00:00"
},
{
data: 4.9875
date: "2015-04-01T00:00:00"
}
]
其他信息 当我的数据从我的角度服务返回时,我似乎没有设置一些东西。如果我在 vm.data 中对数据进行硬编码,图表看起来很好,但是当我切换到从我的服务接收数据时,所有日期都是 12 月 69 日。下面是我对服务的调用以及我的数据对象。
vm.averageZone = [];
var request = new requestObject();
shipmentService.getBasicChartData(request)
.then(function(result) {
vm.averageZone = result.data;
//vm.data = [
// {
// "key": "Average",
// "bar": true,
// "values": vm.averageZone
// }
//];
});
vm.data = [
{
"key" : "Average" ,
"bar": true,
"values" : vm.averageZone
}];
关于我的数据以及从服务返回时应该如何设置这些数据,我是否遗漏了什么?
解决方案 下面是最终的工作。我删除了下面的 vm.data。
vm.averageZone = [];
var request = new requestObject();
shipmentService.getBasicChartData(request)
.then(function(result) {
vm.averageZone = result.data;
vm.data = [
{
"key": "Average",
"bar": true,
"values": vm.averageZone
}
];
});
【问题讨论】:
-
您的数据是什么样的?你能把它放在一个 plunker 或添加一个 sn-p 吗?
-
我已经用数据样本更新了这个问题。
-
格式有点奇怪,但this plunker 是否显示您要查找的内容?我不知道您是否要渲染图表,但 nvd3 希望您的数据有一个名为
values的属性(至少)来构建您的 x 域和范围,所以我重新格式化了您的数据相应地反对。