我跟随json:
[
{"data"=>"data1", "value1"=>10, "value2"=>6, "day"=>"05-20-2016"},
{"data"=>"data1", "value1"=>17, "value2"=>10, "day"=>"05-21-2016"},
{"data"=>"data1", "value1"=>12, "value2"=>8, "day"=>"05-22-2016"},
{"data"=>"data2", "value1"=>5, "value2"=>1, "day"=>"05-20-2016"},
{"data"=>"data2", "value1"=>11, "value2"=>3, "day"=>"05-21-2016"},
{"data"=>"data2", "value1"=>25, "value2"=>18, "day"=>"05-22-2016"}
]
我想要的是在带有C3.js的折线图中显示这些值,并为每个值分别显示一行。
基于这个例子,我希望有一行用于data1和value1,一行用于data1和value2,一行用于data2和value1,一行用于data2和value2,在图例中我想要有Value1>
现在,当我在C3.js中加载它时,它只显示2行(一行用于data1,一行用于data2)。
有人能告诉我到底该怎么做吗?
答案 0 :(得分:0)
这是一个数据争论练习,你想要转换像
这样的数据{"data"=>"data1", "value1"=>10, "value2"=>6, "day"=>"05-20-2016"},
...
{"data"=>"data2", "value1"=>5, "value2"=>1, "day"=>"05-20-2016"},
类似
{"data1value1"=>10, "data1value2"=>6,
"data2value1"=>17, "data2value2"=>10, "key"=>"05-20-2016"},
这可以这样实现:
var json = [
{"data":"data1", "value1":10, "value2":6, "day":"05-20-2016"},
{"data":"data1", "value1":17, "value2":10, "day":"05-21-2016"},
{"data":"data1", "value1":12, "value2":8, "day":"05-22-2016"},
{"data":"data2", "value1":5, "value2":1, "day":"05-20-2016"},
{"data":"data2", "value1":11, "value2":3, "day":"05-21-2016"},
{"data":"data2", "value1":25, "value2":18, "day":"05-22-2016"}
];
var valFields = ["value1", "value2"];
var dataIndexField = "data";
var keyField = "day";
var newMap = {}; // new data will be built up in here
json.forEach (function (d) {
// get new data obj for key, which in this case is the day value
var key = d[keyField];
var newObj = newMap[key];
if (!newObj) { // make the obj if it doesn't exist
newObj = {key: key};
newMap[key] = newObj;
}
// in this obj merge the dataIndexField and valFields to make new datapoints
var dataIndex = d[dataIndexField]; // either data1 or data2
valFields.forEach (function (vField) { // vfield will loop value1 then value2
newObj[dataIndex+vField] = d[vField]; // data1/2value1/2 = the value of value1/2
});
});
var newJson = d3.values(newMap); // array of objs suitable for c3
// dataFields are the names of the new datapoint properties minus 'key'
var newDataFields = d3.keys(newJson[0]);
newDataFields.splice (newDataFields.indexOf("key"), 1);
var chart = c3.generate({
data: {
json: newJson,
keys: {
x: 'key',
value: newDataFields
}
},
axis: {
x: {
type: 'category'
}
}
});
http://jsfiddle.net/w7o8k40q/3/
基本上,中间的位合并了data1 / 2和value1 / 2数字,就像你问的那样,并将它们添加到具有唯一键的对象中,在这种情况下取自每行的day字段。 newJson的Json.stringified输出如下:
[
{"key":"05-20-2016","data1value1":10,"data1value2":6,"data2value1":5,"data2value2":1},
{"key":"05-21-2016","data1value1":17,"data1value2":10,"data2value1":11,"data2value2":3},
{"key":"05-22-2016","data1value1":12,"data1value2":8,"data2value1":25,"data2value2":18}
]
如果你告诉它每行中哪些属性是数据(这是newDataFields
做什么)以及哪一个是x值的关键(PS,因为我们将关键字解释为分类值),这对c3来说已经足够了你可能需要通过关键字段对json进行排序,这样日子就不会出现反过来了 - 幸运的是我们在原始数据集中按顺序遇到它们了)