Search code examples
javascriptjsonpie-chartcanvasjs

Dynamically determine number of pie charts to be displayed and display each one on a single page using CanvasJS


I am hoping to construct an undetermined amount of pie charts and be able to display them alongside each other on a page. The number of pie charts generated will depend upon the number of elements in a JSON object. I have included an example of how my data will look below:

[
  {
    "id" : "123",
    "data" : [20, 40, 10, 20, 10]
  },
  {
    "id" : "456",
    "data" : [10, 20, 20, 30, 20]    
  },
  {
    "id" : "789",
    "data" : [25, 35, 5, 10, 25]
  }
]

I would like to have one pie chart for each element where there is an ‘id’ and ‘data’ attribute. ‘data’ will be used as the dataPoints in the pie charts for the ‘id’ which is included in the element. How can I achieve this?


Solution

  • Parsing data from JSON and passing it to chart-options works. Find the code below:

    var dps = [];
    var dataSeries = [];
    var charts = [];
    
    $.when( $.getJSON("https://api.myjson.com/bins/us9mk", function(result) {  
      for(var i = 0; i < result.length; i++) {
        dps = [];
        for(var j = 0; j < result[i].data.length; j++) {
          dps.push({y: result[i].data[j]});
        }
        dataSeries.push({id: result[i].id, type: "pie", dataPoints: dps})
      }
    })).then(function( data, textStatus, jqXHR ) {
      for(var i = 0; i < dataSeries.length; i++) {
        $("#chartsContainer").append("<div id='" + dataSeries[i].id + "' style='width: 100%; height: 200px;'></div>");
        charts[i] = new CanvasJS.Chart(dataSeries[i].id, {
          title: {
            text: dataSeries[i].id
          },
          data: [dataSeries[i]]
        });    
        charts[i].render();
      }
    });
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="chartsContainer"></div>