从json数据动态创建highcharts中的柱形图

时间:2016-02-04 16:34:53

标签: javascript jquery highcharts

我有以下json数据

var json= {
    "PFTs_likely_to_change": [
        [16]
    ],
    "PFTs_likely_to_remain_unchanged": [
        [2]
    ]
}

此数据来自网址

var data=$.getJSON('{% url "PFTpercentChange" %}');

然后我解析json数据

var json = JSON.parse(data);

现在我想使用highcharts创建柱形图。代码是

$(document).ready(function() {
  $("#container").dialog({
    autoOpen: false,
    width: 600,
    height: 500

  });
  $("#btnclick").click(function() {
    $("#container").dialog("open");
    //var json = JSON.parse(data);
    var json = {
      "PFTs_likely_to_change": [
        [16]
      ],
      "PFTs_likely_to_remain_unchanged": [
        [2]
      ]
    };
    //var chart1; // globally available
    chart1 = new Highcharts.Chart({
      chart: {
        renderTo: 'container',
        type: 'column' // change with your choice
      },
      title: {
        text: 'Change in Plant Functional Types'
      },
      xAxis: {
        categories: ['Change in Plant Functional Types']
          // Should be replace with JSON
      },
      yAxis: {
        title: {
          text: 'Percentage(%)'
        }
      },
      series: [{ //Should be replace with JSON
        name: 'PFTs likely to change',
        data: [88]
      }, {
        name: 'PFTs likely to remain unchanged',
        data: [12]
      }]
    });
  });
});

我该如何动态地执行此操作?

1 个答案:

答案 0 :(得分:1)

更新 Fiddle with chart in dialog with dynamic json data

Here is working fiddle

为弹出/模态设置单独的div。现在把你的高图容器div放进去吧。 更改代码以动态获取系列数据,如下所示:

 var json= {
"PFTs_likely_to_change": [
    [16]
],
"PFTs_likely_to_remain_unchanged": [
    [2]
]
 }
var seriesData=[];
$.each(json,function(key,val){
console.log(key+"----key----and value"+val);
seriesData.push({name:key,data:val}); //put seriesData in chart's series
});