简体   繁体   中英

Create a HighCharts pie chart using JSON Data

I am trying to plot a pie chart using JSON data returned from cartoDB SQL .

I am using the example provided on the High Charts website but the chart is not loading. Below is my javascript code. Can you see anything wrong?

$(document).ready(function() {
  var options = {
      chart: {
        renderTo: 'container',
        type: 'pie'
      },
      series: [{}]
  };

  var jsonURL = 'https://1025.cartodb.com/api/v2/sql?&q=SELECT status FROM kenya_primary_schools';

  $.getJSON(jsonURL, function(data) {
    var obj = data.rows, hObj = [];
    if(obj.length){
      for(var i=0; i<obj.length; i++){
        hObj.push([obj[i]['status']]);
      }
      console.log(hObj);
    }
    options.series[0].data = data;
    var chart = new Highcharts.Chart(options);
  });
});

After modifying your code to some extend, I managed to get the following result:

私人VS公共饼图

Key points you should do

You would need to check from the Highcharts documentation on how the data object is given to series.data from the Highcharts doc

Since you have two options from the cartoDB : PRIVATE and PUBLIC, you should think how to store them in a array/object and how to then form the data object from the pie chart.

Hint:

options.series[0].data = data;

hObj.push([obj[i]['status']]);

There are some syntax errors in your code. You may try correcting like this and give it another try.

$(document).ready(function() {
var options = {
    chart: {
        renderTo: 'container',
            type: 'pie'
    },
   series: [{}]
},
    jsonURL = 'https://1025.cartodb.com/api/v2/sql?&q=SELECT status FROM kenya_primary_schools';

$.getJSON(jsonURL, function(data) {
  var obj = data.rows,
     hObj = [],
    chart;
  if (obj.length) for (var i=0; i<obj.length; i++) hObj.push([obj[i].status]);
  options.series[0].data = data;
  chart = new Highcharts.Chart(options);
});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM