Fill gaps in NVD3.js

痞子三分冷 提交于 2019-12-08 02:56:18

问题


I am trying to make horizontal grouped stacked bar graph in NVD3.js. Everything works great until I got a "gap" in my JSON data like bellow:

 [{
       "key": "Education & news",
           "values": [{
           "label": "2014-02-26",
               "value": 702
       }, {
           "label": "2014-02-27",
               "value": 204
       }, {
           "label": "2014-02-28",
               "value": 3213
       }]
   }, {
       "key": "Entertainment",
           "values": [{
           "label": "2014-02-26",
               "value": 21
       },
//Missing entry for 2014-02-27
       {
           "label": "2014-02-28",
               "value": 3213
       }]
   }]

The error which I got is Uncaught TypeError: Cannot read property '1' of undefined in d3.js. The example and the error of the problem I put on http://jsfiddle.net/vaa3V/

Can I somehow fill gaps automatically?


回答1:


@shabeer90's comment is on track. You can use underscore.js to get the domain values and apply a sensible default.

//Find domain values
DEFAULT = 0
defaults = _.chain(data)
  .pluck('values')
  .flatten().pluck('label')
  .uniq()
  .value()
  .map( function(item){ return {label:item, value:DEFAULT} })

// Group by 'label' so we can apply defaults
defaults = _.groupBy(defaults, 'label'))

// Apply defaults 
_.each(data, function (series) {  
    grouped = _.groupBy(series.values, 'label')
    series.values =  _.flatten( _.defaults(grouped, defaults)) 
})

Should give you:

[
   {
      "key": "Education & news",
      "values": [
         {
            "label": "2014-02-26",
            "value": 702
         },
         {
            "label": "2014-02-27",
            "value": 204
         },
         {
            "label": "2014-02-28",
            "value": 3213
         }
      ]
   },
   {
      "key": "Entertainment",
      "values": [
         {
            "label": "2014-02-26",
            "value": 21
         },
         {
            "label": "2014-02-28",
            "value": 3213
         },
         {
            "label": "2014-02-27",
            "value": 0
         }
      ]
   }
]


来源:https://stackoverflow.com/questions/22351725/fill-gaps-in-nvd3-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!