C3 - 带有JSON和类别的时间序列图表

时间:2016-11-05 13:34:40

标签: json d3.js charts c3.js timeserieschart

我第一次使用C3库,我认为它是D3的一个很好的替代品,用于设计简单且可重复使用的图表而不会产生任何痛苦。

但是,我在设计时间序列图时遇到了一些问题。 以下是我将用于生成图表的JSON文件的示例:

data: {
  json: [
   {
      "city": "Paris",
      "date": "2016-09-01",
      "event": 234
   },
   {
      "city": "Paris",
      "date": "2016-09-02",
      "event": 891
   },
   {
      "city": "Paris",
      "date": "2016-09-03",
      "event": 877
   },
   {
      "city": "Berlin",
      "date": "2016-09-01",
      "event": 190
   },
   {
      "city": "Berlin",
      "date": "2016-09-02",
      "event": 234
   },
   {
      "city": "Berlin",
      "date": "2016-09-03",
      "event": 231
   },
   {
      "city": "London",
      "date": "2016-09-01",
      "event": 23
   },
   {
      "city": "London",
      "date": "2016-09-02",
      "event": 12
   },
   {
      "city": "London",
      "date": "2016-09-03",
      "event": 89
   },
 ],

问题在于我无法将我的轴x:设置为时间序列类型,将关键字“city”设置为类别类型。

现在我有:

keys: {
   x: 'period',
   value: ['event'],
},
axis: {
 x: {
   type: 'timeseries',
   tick: {
     format: '%Y-%m-%d'
   }
 }
},
type: 'spline'

相应的Plunker:http://plnkr.co/edit/T1aLWQpaFwdu2zsWCa3d

我想有3个样条线,对应于从JSON文件中检索到的3个城市。

你能帮助我实现这个目标吗?

非常感谢:)

1 个答案:

答案 0 :(得分:2)

您需要将数据压缩为c3可接受的格式,这与此处的示例类似 - > https://jsfiddle.net/maxklenk/k9Dbf/

对于你们,我们需要一系列条目,如

[{
    date = val
    London = val
    Paris = val
    Berlin = val
},
...
]

要做到这一点,我们需要操纵原始的json:

     var json = <defined here>

      // group json by date
      var nestedData = d3.nest().key(function(d) { return d.date; }).entries(json);
      var cities = d3.set();   // this keeps a record of the cities mentioned so we don't need to hard-code them later on
      // run through the dates and make new objects of city=entry pairs (and the date=whatever)
      // all stored in a new array (formattedData) which we can feed to the chart json argument
      var formattedData = nestedData.map (function (entry) {
        var values = entry.values;
        var obj = {};
        values.forEach (function (value) {
          obj[value.city] = value.event;
          cities.add(value.city);
        })
        obj.date = entry.key;
        return obj;
      });


      var chart = c3.generate({
        data: {json: formattedData,
            keys: {
                x: 'date', // it's possible to specify 'x' when category axis
                value: cities.values(),
            }
        },
...

请参阅http://plnkr.co/edit/5xa4z27HbHQbjcfpRLpQ?p=preview

上编辑过的plunkr