我正在尝试使用NVD3库制作图表但我无法使用JSON网址正常使用该代码。
图表脚本:
d3.json("jsondata3.json",function(error,data){
var chart;
nv.addGraph(function() {
chart = nv.models.linePlusBarChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.margin({top: 30, right: 20, bottom: 50, left: 175})
chart.y1Axis.tickFormat(d3.format(',f'));
chart.y2Axis.tickFormat(d3.format(',f'));
d3.select('#chart svg')
.datum(data)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
chart.dispatch.on('stateChange', function(e) { nv.log('New State:', JSON.stringify(e)); });
return chart;
});
});
JSON数据格式:
[{"TRANSACTION_DAY":"20130620","MT_ATTEMPTED":4505891,"MT_SUCCESS":83.54,"MO_ATTEMPTED":321857,"MO_SUCCESS":98.9},{"TRANSACTION_DAY":"20130621","MT_ATTEMPTED":6636631,"MT_SUCCESS":81.33,"MO_ATTEMPTED":311954,"MO_SUCCESS":98.66},{"TRANSACTION_DAY":"20130622","MT_ATTEMPTED":2708897,"MT_SUCCESS":90.47,"MO_ATTEMPTED":334279,"MO_SUCCESS":98.95} ]
示例附带此代码(显然可以正常工作),但我发现它与我的JSON数据的格式略有不同。此外还使用了“map.series.values”函数。
var testdata = [
{
"key" : "Quantity" ,
"bar": true,
"values" : [ [ 1327986000000 , 690033.0] , [ 1330491600000 , 690033.0] , [ 1333166400000 , 514733.0] , [ 1335758400000 , 514733.0]]
},
{
"key" : "Price" ,
"values" : [ [ 1322629200000 , 382.2] , [ 1325307600000 , 405.0] , [ 1327986000000 , 456.48] , [ 1330491600000 , 542.44] , [ 1333166400000 , 599.55] , [ 1335758400000 , 583.98] ]
}
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
那么如何使用此代码使我的JSON文件正常工作?我迷路了...
答案 0 :(得分:0)
我认为你仍然需要格式化你的json数据与样本数据的格式完全相同。试试这个。
注意:javascript时间戳以毫秒为单位,因此您应将时间戳(20130620等)转换为unix时间戳和多个1000.
var testdata = [
{
"key" : "MT_ATTEMPTED" ,
"bar": true,
"values" : [ [ 4505891 , 20130620] , [ 6636631 , 20130621] , [ 2708897 , 20130622] ]
},
{
"key" : "MT_SUCCESS" ,
"values" : [ [ 83.54 , 20130620] , [ 81.33 , 20130621] , [ 90.47 , 20130622] ]
},
{
"key" : "MO_ATTEMPTED" ,
"values" : [ [ 321857 , 20130620] , [ 311954 , 20130621] , [ 334279 , 20130622] ]
},
{
"key" : "MO_SUCCESS" ,
"values" : [ [ 98.9 , 20130620] , [ 98.66 , 20130621] , [ 98.95 , 20130622] ]
},
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});
var testdata = [
{
"key" : "MT_ATTEMPTED" ,
"bar": true,
"values" : [ [ 4505891 , 20130620] , [ 6636631 , 20130621] , [ 2708897 , 20130622] ]
},
{
"key" : "MT_SUCCESS" ,
"values" : [ [ 83.54 , 20130620] , [ 81.33 , 20130621] , [ 90.47 , 20130622] ]
},
{
"key" : "MO_ATTEMPTED" ,
"values" : [ [ 321857 , 20130620] , [ 311954 , 20130621] , [ 334279 , 20130622] ]
},
{
"key" : "MO_SUCCESS" ,
"values" : [ [ 98.9 , 20130620] , [ 98.66 , 20130621] , [ 98.95 , 20130622] ]
},
].map(function(series) {
series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } });
return series;
});