2016-11-05 58 views
0

我第一次使用C3库,我认为这是一个很好的替代D3设计简单和可重复使用的图表没有痛苦。C3 - 与JSON和类别的时间序列图

但是,我在设计时间序列图时遇到了一些问题。 这里是我会用它来生成我的图表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轴:作为一个时间序列类型和密钥“城市”作为一个类别类型。

现在我有:

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

您需要将您的数据缠斗成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(), 
      } 
     }, 
... 

查看编辑plunkr在http://plnkr.co/edit/5xa4z27HbHQbjcfpRLpQ?p=preview

+0

谢谢@mgraham,你让我的一天!这正是我一直在寻找的:)感谢plunkr – Bikemat