Google Charts con PHP (Gráfica de Barras Múltiples)

Hola tyros, en esta ocasión les voy a mostrar como crear una gráfica de barras múltiples (agrupadas) en PHP.

Lo primero que necesitamos es nuestra clase "Charts.php":

<?php

/**
 * Clase para generar Json aceptable por Google Charts
 *
 * @author gabriel.castillo / tyrodeveloper
 */
class Charts {

    //put your code here
    public $cols;
    public $rows;

}

class ChartColumn {

    public $id;
    public $label;
    public $pattern;
    public $type;
    public $role;

}

class ChartRow {

    public $c;

}

class ChartRowValue {

    public $v;
    public $f;

}
?>

Ahora, nuestra página "grafica-barras-multiples.php"

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>TyroDeveloper</title>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"
                integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>
        <script src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript">

            google.charts.load('current', {'packages': ['corechart']});

            google.charts.setOnLoadCallback(drawChart);


            function drawChart() {
                //Barras
                $.ajax({
                    type: 'POST',
                    url: "grafica-barras-multiples.php",
                    dataType: "json",
                    contentType: 'application/json',
                    async: false,
                    success: function (result) {
                        var data = new google.visualization.DataTable(result);
                        var options = {
                            title: '',
                            hAxis: {
                                title: 'Meses del Año'
                            },
                            vAxis: {
                                title: 'Total'
                            },
                            pointSize: 5,
                            backgroundColor: {fill: 'transparent'},
                            'height': 300,
                            colors:['#FF0000','#00CC00','#9900CC']
                        };
                        target = document.getElementById('bar-chart');
                        var chart = new google.visualization.ColumnChart(target);
                        chart.draw(data, options);
                    }
                });

            }
        </script>
        <style>
            body {
                font-family: Verdana;
            }
        </style>
    </head>
    <body>
        <form id="frmChart" runat="server">
            <div>
                <div id="bar-chart"></div>
            </div>
        </form>
    </body>
</html>

El código del archivo "grafica-barras-multiples.php"

<?php

include ("Charts.php");
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$chart = new Charts();

//Inicializar columnas
$chart->cols = array();
//Inicializar filas
$chart->rows = array();

//agregar columnas
//Mes
$chart_column = new ChartColumn();
$chart_column->label = "Mes";
$chart_column->type = "string";
array_push($chart->cols, $chart_column);
$chart_column = new ChartColumn();
//Fresas
$chart_column->label = "Fresas";
$chart_column->type = "number";
array_push($chart->cols, $chart_column); 
//Fresas - Estilo
$chart_column = new ChartColumn();
$chart_column->role="style";
$chart_column->type = "string";
array_push($chart->cols, $chart_column);
//Manzanas
$chart_column = new ChartColumn();
$chart_column->label = "Manzanas";
$chart_column->type = "number";
array_push($chart->cols, $chart_column); 
//Manzanas - Estilo
$chart_column = new ChartColumn();
$chart_column->role="style";
$chart_column->type = "string";
array_push($chart->cols, $chart_column);
//Uvas
$chart_column = new ChartColumn();
$chart_column->label = "Uvas";
$chart_column->type = "number";
array_push($chart->cols, $chart_column); 
//Uvas - Estilo
$chart_column = new ChartColumn();
$chart_column->role="style";
$chart_column->type = "string";
array_push($chart->cols, $chart_column);

//Agregar datos
//Agregar Enero
$chart_row = new ChartRow();
$chart_row->c = array();
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "Enero";
array_push($chart_row->c, $chart_row_value);
//Fresas - Valor
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 20;
array_push($chart_row->c, $chart_row_value);
//Fresas - Estilo
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#FF0000";
array_push($chart_row->c, $chart_row_value);
//Manzanas Valor
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 5;
array_push($chart_row->c, $chart_row_value);
//Manzanas - Estilo
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#00CC00";
array_push($chart_row->c, $chart_row_value);
//Uvas - Valor
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 13;
array_push($chart_row->c, $chart_row_value);
//Uvas - EStilo
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#9900CC";
array_push($chart_row->c, $chart_row_value);
//Agregar Fila (Enero)
array_push($chart->rows, $chart_row);

//Agregar Febrero
$chart_row = new ChartRow();
$chart_row->c = array();
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "Febrero";
array_push($chart_row->c, $chart_row_value);
//Fresas - Valor
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 12;
array_push($chart_row->c, $chart_row_value);
//Fresas - Estilo
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#FF0000";
array_push($chart_row->c, $chart_row_value);
//Manzanas Valor
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 21;
array_push($chart_row->c, $chart_row_value);
//Manzanas - Estilo
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#00CC00";
array_push($chart_row->c, $chart_row_value);
//Uvas - Valor
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 12;
array_push($chart_row->c, $chart_row_value);
//Uvas - EStilo
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#9900CC";
array_push($chart_row->c, $chart_row_value);
//Agregar Fila (Febrero)
array_push($chart->rows, $chart_row);


echo json_encode($chart);


Finalmente, así se ve nuestra gráfica:

No hay comentarios:

Publicar un comentario