JSON data format in NVD3 chart

我的梦境 提交于 2019-12-25 16:10:21

问题


I have a chart template for a multi bar chart in NVD3 here: http://jsfiddle.net/hohenheim/6R7mu/5/

I have the following JSON data I want to display:

[{"date": 1396828800, "impressions": 49145385},
{"date": 1396915200, "impressions": 46704447},
{"date": 1397001600, "impressions": 47181000},
{"date": 1397088000, "impressions": 47337965},
{"date": 1397174400, "impressions": 51129266},
{"date": 1397260800, "impressions": 60547397},
{"date": 1397347200, "impressions": 62217077},
{"date": 1397433600, "impressions": 49145385},
{"date": 1397520000, "impressions": 46704447},
{"date": 1397606400, "impressions": 47181000},
{"date": 1397692800, "impressions": 47337965},
{"date": 1397779200, "impressions": 51129266},
{"date": 1397865600, "impressions": 60547397},
{"date": 1397952000, "impressions": 62217077}]

I'm looking to use JSON data I have (shown above and also commented out in the fiddle) but don't have any idea how to get it in the format that this NVD3 chart will accept. The chart is currently using sample data that is meaningless to me.

Is there a way to convert my data into something NVD3 will accept? Any help appreciated.


回答1:


data5 seems to have this format:

[
  {key: x, values: VALUES, vAxis: 1},
  {key: x, values: VALUES, vAxis: 1} // and maybe more for more colors
]

and VALUES seems to have this format:

[
  {x: 0, y: N},
  {x: 1, y: N},
  {x: 2, y: N} // and more for more on the X axis
]

So you have to rewrite your data to that format. Only it seems you don't have more sources. You have only 1 color. What makes {"date": 1396828800, "impressions": 49145385} one or the other? Is date the X axis?

Assuming the order of your data is correct, and it's only 1 source:

data5 = [{key: 'X', values: [], vAxis: 1}]
yourData.forEach(function(el, i) {
  data5[0].values.push({x: i, y: el.impressions});
     // ^ only 1 source/color
                        // ^ incremental X, starting at 0
});

You might have to adjust the x and y range somehow. (Maybe vAxis is one?)




回答2:


I just stumbled upon their github page, and seems the above answer is correct.

https://github.com/novus/nvd3/wiki/Sample-chart-(your-first-nvd3-chart!) The data format for charts is supposed to be:

[
    {
        key: "<Series name>",
        color: "<CSS color>",
        values: [
            {x: 0, y: 10},
            {x: 1, y: 20},
            {x: 2, y: 30}
            ....
        ]
    },
    {
        key: "<Series name>"
        ...
    }
]


来源:https://stackoverflow.com/questions/23643487/json-data-format-in-nvd3-chart

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