Pie Chart in PHP with MySql using Google API Tutorial

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 Chart using Google API. In this tutorial, we will create database to get data to create dynamic Pie Chart. We use codeigniter framework for PHP. You can use any script to get data from database. We create a Controllers and Model to get data and pass it into view to display in charts. We will use Google Charts loader to load Pie chart.

Create Database

We need to get data from database to create dynamic chart, hence we will create Database. After successfully created database, we need to create a table. The structure and data of table given below:

--
-- Table structure for table `company_performance`
--

CREATE TABLE IF NOT EXISTS `company_performance` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `year` int(10) NOT NULL,
  `sales` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

--
-- Dumping data for table `company_performance`
--

INSERT INTO `company_performance` (`id`, `year`, `sales`) VALUES
(1, 2016, 1000),
(2, 2015, 880),
(3, 2014, 960),
(4, 2013, 660),
(5, 2012, 1120),
(6, 2011, 1500);

Create a Model

We need to create a Model to create a function to get data to display in a Pie Chart, so we will create a data_model.php file into appliaction/model directory. Now, we are going to create a function to get data from company_performance table and return it in array.

<?php

class Data_model extends CI_Model {

    /**
     * @desc load  db
     */
    function __construct() {
        parent::__Construct();
        $this->db = $this->load->database('default', TRUE, TRUE);
    }

    /**
     * @desc: Get data from company_performance table
     * @return: Array()
     */
    function getdata(){
		$this->db->select('*');
		$query = $this->db->get('company_performance');
		return $query->result_array();

    }
}

Create Controller

We will create a controller to get data from model and load view. We will create a charts.php file in the application/controllers directory. In this controller we will create a function to load view and another function to get the data to call model.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Charts extends CI_Controller {

	function __Construct() {
        parent::__Construct();

        $this->load->helper(array('form', 'url'));
        $this->load->model('data_model');
      
    }
    /**
     * @desc: This method is used to load view
     */
	public function index()
	{

		$this->load->view('piechart');
	}
    /**
     * @desc: This method is used to get data to call model and print it into Json
     * This method called by Ajax
     */
	function getdata(){
		$data  = $this->data_model->getdata();
		print_r(json_encode($data, true));
	}
}

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 script.

Ajax Call to Get Data

To get data(Json data) from database, we need to use ajax to send a request to get data from database. onsuccess of ajax call, 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() {
              $.ajax({
                type: 'POST',
                url: 'http://localhost/charts/charts/getdata',
                success: function (data1) {
                  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

Data got from PHP script as in json hence parse it into Json in js. 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() {
              $.ajax({
                type: 'POST',
                url: 'http://localhost/charts/charts/getdata',
                success: function (data1) {
                  var data = new google.visualization.DataTable();
                  // Add legends with data type
                  data.addColumn('string', 'Year');
                 data.addColumn('number', 'Sales');
                 //Parse data into Json
                 var jsonData = $.parseJSON(data1);
                 for (var i = 0; i < jsonData.length; i++) {
                   data.addRow([jsonData[i].year, parseInt(jsonData[i].sales)]);
                 }
               }
            });
          }
       </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() {
              $.ajax({
                type: 'POST',
                url: 'http://localhost/charts/charts/getdata',
                success: function (data1) {
                  var data = new google.visualization.DataTable();
                  // Add legends with data type
                  data.addColumn('string', 'Year');
                 data.addColumn('number', 'Sales');
                 //Parse data into Json
                 var jsonData = $.parseJSON(data1);
                 for (var i = 0; i < jsonData.length; i++) {
                   data.addRow([jsonData[i].year, parseInt(jsonData[i].sales)]);
                 }
                 
                 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 display, 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