【问题标题】:Is it possible to generate a graph in nvd3.js using this data?是否可以使用这些数据在 nvd3.js 中生成图表?
【发布时间】:2016-05-17 21:12:53
【问题描述】:

我有一个输出以下内容的小函数:

[
    {
        "label": "A",
        "value": 101.23
    },
    {
        "label": "B",
        "value": 109.87
    },
    {
        "label": "C",
        "value": 107.34
    },
    {
        "label": "D",
        "value": 115.17
    },
    {
        "label": "E",
        "value": 119.61
    }
]

我正在尝试并惨遭失败的是使用该数据生成图表。我想用 nvd3 或 d3 生成一个简单的条形图。

我拥有的是这样的:

var output = [];

Object.keys(input.Data).forEach(function(key){
    if(key.indexOf('mean') > -1){
    output.push({label: key,value: input.Data[key]});
    }
});

nv.addGraph(function() {
    var chart = nv.models.discreteBarChart()
        .x(function (d) {return d.label})
        .y(function (d) {return d.value})


    d3.select('#chart svg')
        .datum(output)
        .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
});

我收到 TypeError: cannot read property 'length' of undefined.

我对 nvd3 或 d3 不够熟悉,无法追踪到这一点,但这可能与版本不匹配有关。我正在使用 d3 v3.5.1 和 nvd3 v1.8.3。不过只是猜测。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript d3.js charts nvd3.js


    【解决方案1】:

    数据必须采用这种格式。

    output = [{
      key: "",
      values: [{
        "label": "A",
        "value": 101.23
      }, {
        "label": "B",
        "value": 109.87
      }, {
        "label": "C",
        "value": 107.34
      }, {
        "label": "D",
        "value": 115.17
      }, {
        "label": "E",
        "value": 119.61
      }]
    }]
    

    工作代码here

    【讨论】:

      猜你喜欢
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 2020-11-30
      相关资源
      最近更新 更多