Make pie charts - Javascript Google Chart

Javascript examples for Google Chart:Pie Chart

Description

Make pie charts

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 
      <script type="text/javascript">
       google.charts.load('current', {'packages':['corechart']});
         google.charts.setOnLoadCallback(drawChart);
      var dbData = [{//from w w w  .  j  av a 2s .  c  o  m
         "Year": 2014,
         "Name": "A",
         "Values": 18
      }, {
         "Year": 2014,
         "Name": "B",
         "Values": 16
      }, {
         "Year": 2015,
         "Name": "D",
         "Values": 20
      }, {
         "Year": 2015,
         "Name": "C",
         "Values": 0
      }, {
         "Year": 2015,
         "Name": "A",
         "Values": 0
      }, {
         "Year": 2016,
         "Name": "D",
         "Values": 19
      }];
      var yearFieldName = "Year";
      var nameFieldName = "Name";
      var valuesFieldName = "Values";
      function createPieChartData(data, keyTitle, valueTitle) {
         var yearGroups = {};
         var result = [];
         result.push([keyTitle, valueTitle]);
         var year = null;
         for (var i = data.length - 1; i >= 0; i--) {
            year = data[i][yearFieldName];
            if (typeof year === "number" || typeof year === "string") {
               if (typeof yearGroups[year] === "undefined") {
                  yearGroups[year + ""] = 0;
               }
               yearGroups[year] += data[i][valuesFieldName];
            } 
         }
         for(var y in yearGroups) {
            result.push([y, yearGroups[y]]);
         }
         return result;
      }
      function drawChart() {
         var data = google.visualization.arrayToDataTable(createPieChartData(dbData, "Year", "Sum of Values"));
         var options = {
           title: 'Values for each year:'
         };
         var chart = new google.visualization.PieChart(document.getElementById('piechart'));
         chart.draw(data, options);
      }
    
      </script> 
   </head> 
   <body> 
      <div id="piechart" style="width: 900px; height: 500px;"></div>  
   </body>
</html>

Related Tutorials