C3 - 包含 JSON 和类别的时间序列图表

C3 - Timeseries chart with JSON and categories

我是第一次使用 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 个城市。

你能帮我实现这个吗?

非常感谢:)

您需要将您的数据转换为 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