使用json对象填充饼图数据的Highcharts

时间:2013-01-18 09:55:17

标签: highcharts

你的json对象看起来像这样

[
  {"name":"Tokyo","data":3.0},
  {"name":"NewYork","data":2.0},
  {"name":"Berlin","data":3.5},
  {"name":"London","data":1.5}
]

如何填充系列点以使用highcharts制作饼图

2 个答案:

答案 0 :(得分:4)

请尝试以下代码。这将解析所有值并创建一个名为dataArrayFinal的数组。

var d = [{"name":"Tokyo","data":3.0},{"name":"NewYork","data":2.0}, {"name":"Berlin","data":3.5},{"name":"London","data":1.5}]
var name = Array();
var data = Array();
var dataArrayFinal = Array();
for(i=0;i<d.length;i++) { 
   name[i] = d[i].name; 
   data[i] = d[i].data;  
}

for(j=0;j<name.length;j++) { 
   var temp = new Array(name[j],data[j]); 
   dataArrayFinal[j] = temp;     
}

你的系列内容应如下所示。即,您应该像下面一样传递数组dataArrayFinal

series: [{
      type: 'pie',
      name: 'Browser share',
      data: dataArrayFinal
}]

答案 1 :(得分:2)

实际上,您的数据定义与Highcharts要求的格式之间的唯一区别是,您的数据属性称为“数据”,Highcharts期望“y”。所以你只需要遍历数据并设置该属性。请在http://jsfiddle.net/highcharts/uTyZk/直播。

// Original data
var data = [{
    "name": "Tokyo",
    "data": 3.0
}, {
    "name": "NewYork",
    "data": 2.0
}, {
    "name": "Berlin",
    "data": 3.5
}, {
    "name": "London",
    "data": 1.5
}];

// Highcharts requires the y option to be set
$.each(data, function (i, point) {
    point.y = point.data;
});


var chart = new Highcharts.Chart({

    chart: {
        renderTo: 'container',
        type: 'pie'
    },

    series: [{
        data: data
    }]

});