Google Charts con PHP (Gráfica de Barras)

Hola tyros, yo de nuevo. Hoy les voy a mostrar la versión PHP de la gráfica de Barras.

Ver versión para ASP.Net

Primero necesitamos nuestra versión PHP de la clase "Charts", la cual es como sigue:


<?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, necesitamos crear un archivo PHP "grafica-barras.php", el cual genera la infirmación a mostrar:

<?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();


$chart->cols = array();
$chart->rows = array();

//agregar columnas
//col1
$chart_column = new ChartColumn();
$chart_column->id = "";
$chart_column->label = "Tipo";
$chart_column->pattern = "";
$chart_column->type = "string";
array_push($chart->cols, $chart_column); //col1
//col2
$chart_column = new ChartColumn();
$chart_column->id = "";
$chart_column->label = "Total";
$chart_column->pattern = "";
$chart_column->type = "number";
array_push($chart->cols, $chart_column); //col2
//col3 - estilos
$chart_column = new ChartColumn();
$chart_column->role="style";
$chart_column->type = "string";
array_push($chart->cols, $chart_column); //estilos

//Agregar datos
//Agregar 20 Fresas
$chart_row = new ChartRow();
$chart_row->c = array();
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "Fresas";
array_push($chart_row->c, $chart_row_value);
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 20;
array_push($chart_row->c, $chart_row_value);

$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#FF0000";
array_push($chart_row->c, $chart_row_value);
array_push($chart->rows, $chart_row);

//Agregar 5 Manzanas
$chart_row = new ChartRow();
$chart_row->c = array();
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "Manzanas";
array_push($chart_row->c, $chart_row_value);
$chart_row_value = new ChartRowValue();
$chart_row_value->v = 5;
array_push($chart_row->c, $chart_row_value);

$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#00CC00";
array_push($chart_row->c, $chart_row_value);
array_push($chart->rows, $chart_row);

//Agregar 13 Uvas
$chart_row = new ChartRow();
$chart_row->c = array();
$chart_row_value = new ChartRowValue();
$chart_row_value->v = "Uvas";
array_push($chart_row->c, $chart_row_value);
$chart_row_value = new ChartRowValue();
$chart_row_value->v =13;
array_push($chart_row->c, $chart_row_value);

$chart_row_value = new ChartRowValue();
$chart_row_value->v = "color:#9900CC";
array_push($chart_row->c, $chart_row_value);
array_push($chart->rows, $chart_row);

echo json_encode($chart);
?>

Por último, nuestra página PHP, llamada "barras.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.php",
                dataType: "json",
                contentType: 'application/json',
                async: false,
                success: function (result) {
                    var data = new google.visualization.DataTable(result);
                    var options = {
                        title: '',
                        hAxis: {
                            title: 'Tipo'
                        },
                        vAxis: {
                            title: 'Total'
                        },
                        legend:{position:'none'},
                        pointSize: 5,
                        backgroundColor: { fill: 'transparent' },
                        'height': 300
                    };
                    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>

Listo, así se ve nuestra gráfica:

No hay comentarios:

Publicar un comentario