Create google pie char from complex array and object - Javascript Google Chart

Javascript examples for Google Chart:Pie Chart

Description

Create google pie char from complex array and object

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Pie Chart Example</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
   </head> 
   <body> 
      <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script> 
      <div id="piechart" style="width: 900px; height: 500px;"></div> 
      <script type="text/javascript">
var myData = '[{"amt":"500","tag":"travel","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"500","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"30","tag":"drinks","date":"2015-11-23"}]';
   var myObj = generateTmpObj(JSON.parse(myData));
    var tmpArray = [['Tag', 'Amount']];
       tmpArray = generate_array_for_DataTable(myObj);
   google.setOnLoadCallback(drawChart(tmpArray));
   function generateTmpObj(data) {
        var tmpObj = {};/*from   w w w  . j  av a 2  s  .co  m*/
        for(var i = 0; i < data.length; i++) {
           if (tmpObj[data[i].tag]) {
               tmpObj[data[i].tag] += parseInt(data[i].amt);
           } else {
               tmpObj[data[i].tag] = parseInt(data[i].amt);
           }
      }
        return tmpObj;
     }
    function generate_array_for_DataTable(data) {
          for (var prop in data) {
            tmpArray.push([prop, data[prop]]);
      }
        return tmpArray;
     }
   function drawChart(data) {
        var data = google.visualization.arrayToDataTable(data);
        var options = {
          title: 'My Pie Chart'
        };
        var chart = new google.visualization.PieChart(document.getElementById('piechart'));
        chart.draw(data, options);
      }

      </script>  
   </body>
</html>

Related Tutorials