将Json数据应用于Barchart -Plotly

时间:2017-08-29 06:15:52

标签: angularjs json bar-chart plotly

我正在使用Plotly绘制条形图。目前我正在提供硬编码数据。但现在我想把json数据gicve到图表。我们如何解析它并使用它。请帮助我,因为我是json的新手。

//下面是图表代码:

   var trace1 = {
       x: ['giraffes', 'orangutans', 'monkeys'],
       y: [20, 14, 23],
       name: 'SF Zoo',
       type: 'bar'
   };
   var trace2 = {
       x: ['giraffes', 'orangutans', 'monkeys'],
       y: [12, 18, 29],
       name: 'LA Zoo',
       type: 'bar'
   };
   var data = [trace1, trace2];
   var layout = {
       barmode: 'group'
   };
   Plotly.newPlot('myDiv', data, layout);

现在我需要牧师JSON数据并将json数据的值分配给x和y轴。

[{"PartList.PartList.COID":"3D3DB2BCF8A50D94", "PartList.PartList.COMPID":3030, "PartList.PartList.C_VERSION":1, "PartList.PartList.NATCO":"null"}, {"PartList.PartList.COID":"3D3DB2BCF8A50D9F", "PartList.PartList.COMPID":3030, "PartList.PartList.C_VERSION":1, "PartList.PartList.NATCO":"null"}, {"PartList.PartList.COID":"3D3DB2BCF8A50D9F", "PartList.PartList.COMPID":3030, "PartList.PartList.C_VERSION":1, "PartList.PartList.NATCO":"null"}]

1 个答案:

答案 0 :(得分:1)

这是一个如何操作的简单示例,请将X和Y轴中的变量名称更改为您想要的任何名称。如果有任何问题,请告诉我。

JSFiddle Demo

<强>代码:

var data = [{"PartList.PartList.COID":"3D3DB2BCF8A50D94", "PartList.PartList.COMPID":3030, "PartList.PartList.C_VERSION":1, "PartList.PartList.NATCO":"null"}, {"PartList.PartList.COID":"3D3DB2BCF8A50D9F", "PartList.PartList.COMPID":3030, "PartList.PartList.C_VERSION":1, "PartList.PartList.NATCO":"null"}, {"PartList.PartList.COID":"3D3DB2BCF8A50D9F", "PartList.PartList.COMPID":3030, "PartList.PartList.C_VERSION":1, "PartList.PartList.NATCO":"null"}]

var traces = [];
data.forEach(function(val){
    var trace = {
    x: [val["PartList.PartList.COMPID"]],
    y: [val["PartList.PartList.C_VERSION"]],
    name: val["PartList.PartList.COID"],
    type: 'bar'
  };
  traces.push(trace);
});
console.log(traces);
   var layout = {
       barmode: 'group'
   };
Plotly.newPlot('tester', traces, layout);