Pie Chart Tutorial in javascript using Google Api

This tutorial explains how to implement Simple Pie Chart, 3D Pie Chart, Donut Chart, Rotating Pie Chart, Exploding a slices and Remove Slices using Google API.




pie_chart

Introduction

A Pie Chart or Pie Graph is a type of graph in which a circle is divided into sectors that each represent a proportion of the whole.

In this tutorial, we will implement Pie Chart using Google API. We will use Google Charts loader to load Pie chart.

Create Pie Chart

To create Pie Chart, we will pass package name corechart in the google.charts.load() object. It will help to display pie chart.

Loading

The google.charts.load package name is "corechart"
google.charts.load("current", {packages: ["corechart"]});

The visualization’s class name is google.visualization.PieChart.

var visualization = new google.visualization.PieChart(container);

We are going to create a drawChart() method in js. In this method, we will initialize a object( Google visualization datatable) to create our data table out of JSON data loaded from server. To add legends to call addColumn() method. We need to pass data type and legends into addColumn() method.

drawChart() function called by callback google.charts.setOnLoadCallback().

<html>
    <head>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
        <script type="text/javascript">
            // Load the Visualization API and the line package.
            google.charts.load('current', {'packages':['corechart']});
            // Set a callback to run when the Google Visualization API is loaded.
            google.charts.setOnLoadCallback(drawChart);
            
            function drawChart() {
                var data = new google.visualization.DataTable();
                // Add legends with data type
                data.addColumn('string', 'Year');
                data.addColumn('number', 'Sales');
            }
       </script>
    </head>
</html>

Add Data Values

To add data values into Pie Chart, we need to pass data values in addRow() method.

<html>
    <head>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
        <script type="text/javascript">
            // Load the Visualization API and the line package.
            google.charts.load('current', {'packages':['corechart']});
            // Set a callback to run when the Google Visualization API is loaded.
            google.charts.setOnLoadCallback(drawChart);
            
            function drawChart() {
                var data = new google.visualization.DataTable();
                // Add legends with data type
                data.addColumn('string', 'Year');
                data.addColumn('number', 'Sales');

               data.addRow(['2016', parseInt('1000')]);
               data.addRow(['2015', parseInt('880')]);
               data.addRow(['2014', parseInt('960')]);
               data.addRow(['2013', parseInt('660')]);
               data.addRow(['2012', parseInt('1120')]);
               data.addRow(['2011', parseInt('1500')]);
               
            }
       </script>
    </head>
</html>

Create a Variable Option

We will create a variable to store title, legends, PieSliesText. Pass the div id where Pie Chart to be display into google.visualization.PieChart() object. Now finally to create Pie chart, call draw() method with data table object and option variable.

<html>
   <head>
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
      <script type="text/javascript">
         // Load the Visualization API and the line package.
         google.charts.load('current', {'packages':['corechart']});
         // Set a callback to run when the Google Visualization API is loaded.
         google.charts.setOnLoadCallback(drawChart);
         
         function drawChart() {
           var data = new google.visualization.DataTable();
           // Add legends with data type
           data.addColumn('string', 'Year');
           data.addColumn('number', 'Sales');
         
            data.addRow(['2016', parseInt('1000')]);
            data.addRow(['2015', parseInt('880')]);
            data.addRow(['2014', parseInt('960')]);
            data.addRow(['2013', parseInt('660')]);
            data.addRow(['2012', parseInt('1120')]);
            data.addRow(['2011', parseInt('1500')]);
         
            var options = {
                legend: '',
                pieSliceText: 'label',
                title: 'Company Sales Performance',
            };
         
            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>

pie_chart

Hide Legends

By default legends will be displayed, if we want to hide legend then set legends: ‘none’ in variable option

var options = {
     pieSliceText: 'label',
     title: 'Company Sales Performance',
     legend: 'none',
};

pie_chart_without_legends

Define Slices Color

If we want to fill custom color into slices then add color into variable option like this:-

 var options = {
      pieSliceText: 'label',
      title: 'Company Sales Performance',
      colors: ['#e0440e', '#e6693e', 'blue', '#f3b49f', '#f6c7b6']
 };

define_color_pie_chart

3D Pie Chart

is3D is false by default, so here we explicitly set it to true:

var options = {
     pieSliceText: 'label',
     title: 'Company Sales Performance',
     is3D: true,
};

3d_pie_chart

Donut Chart

A Donut chart is a pie chart with a hole in the center. You can create donut charts with the pieHole.

The pieHole option should be set to a number between 0 and 1, corresponding to the ratio of radii between the hole and the chart. Numbers between 0.4 and 0.6 will look best on most charts. Values equal to or greater than 1 will be ignored, and a value of 0 will completely shut your piehole.

We can’t combine the pieHole and is3D options, if we do, pieHole will be ignored.

var options = {
     pieSliceText: 'label',
     title: 'Company Sales Performance',
     pieHole: 0.4,
};

donut_chart

Rotating a Pie Chart

By default, pie charts begin with the left edge of the first slice pointing straight up. You can change that with the pieStartAngle option.
Here, we rotate the chart clockwise 150 degrees with an option of pieStartAngle: 150

var options = {
     pieSliceText: 'label',
     title: 'Company Sales Performance',
     pieStartAngle: 150,
};

rotating_pie_chart

Exploding Slices

We can separate pie slices from the rest of the chart with the offset property of the slices option. To separate a slice, create a slices object and assign the appropriate slice number an offset between 0 and 1. Below, we assign progressively larger offsets to slices 1 (2015), 2 (2014):

var options = {
     pieSliceText: 'label',
     title: 'Company Sales Performance',
     slices: {  1: {offset: 0.2},
                2: {offset: 0.3},
     },
};

exploding_slice_pie_chart

Remove Slices

To omit a slice, change the color to ‘transparent’:

var options = {
     pieSliceText: 'label',
     title: 'Company Sales Performance',
     slices: {
            0: { color: 'yellow' },
            1: { color: 'transparent' }
     },
};

remove_slices_pie_chart



The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com