Flotcharts con PHP (Gráfica de Líneas)

Hola tyros!

Hoy les mostraré como crear una gráfica de Líneas con Flotcharts y PHP.

Como ya es costumbre, necesitamos una clase. Así que agregamos un archivo PHP llamado "FlotCharts.php", con el siguiente código:

<?php
/**
 * Description of FlotCharts
 *
 * @author gabriel.castillo
 */
class PieChart {
    public $series;
}

class LineChart{
    public $series;
}

class BarChart{
    public $categories;
    public $series;
}

class Serie{
    public $label;
    public $color;
    public $data;
}
?>

Luego, agregamos una página PHP llamada "lineas.php", con el siguiente código:

<!DOCTYPE html>

<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 type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.time.min.js"></script>
        <script type="text/javascript" src="http://www.jqueryflottutorial.com/js/flot/jquery.flot.axislabels.js"></script>
        <style>
            body {
                font-family: Verdana;
            }
            #tooltip {
                position: absolute;
                display: none;
                border: 1px solid #fdd;
                padding: 2px;
                background-color: #fee;
                opacity: 0.80;
            }
        </style>
        <script type="text/javascript">
            $(document).ready(function () {
                $.ajax({
                    type: 'POST',
                    url: "flotcharts-lineas.php",
                    dataType: "json",
                    contentType: 'application/json',
                    async: false,
                    success: function (result) {
                        var options = {
                            series: {
                                lines: {show: true},
                                points: {show: true}
                            },
                            xaxis: {
                                mode: "time",
                                minTickSize: [1, "day"],
                                timeformat: "%d/%m/%Y",
                                axisLabel: 'Fecha'
                            },
                            yaxis: {
                                axisLabel: "Total"
                            },
                            legend: {
                                show: true
                            },
                            grid: {
                                hoverable: true,
                                clickable: true
                            }
                        };
                        var data = result.series;
                        $.plot($("#line-chart"), data, options);
                        //Configurar tooltip
                        $("#line-chart").bind("plothover", function (event, pos, item) {
                            if (item) {
                                var x = item.datapoint[0],
                                        y = item.datapoint[1].toFixed(2);
                                //Obtener fecha
                                var date = new Date(x);
                                var formattedDate = ('0' + date.getUTCDate()).slice(-2) + '/' +
                                        ('0' + (date.getUTCMonth() + 1)).slice(-2) + '/' +
                                        date.getUTCFullYear();
                                $("#tooltip").html("<b>" + item.series.label + "</b><br />" + formattedDate + " = $" + y)
                                        .css({top: item.pageY + 5, left: item.pageX + 5})
                                        .fadeIn(200);
                            } else {
                                $("#tooltip").hide();
                            }

                        });

                    }
                });
            });
        </script>
    </head>
    <body>
        <form id="frmFlotCharts" runat="server">
            <div id="line-chart" style="width: 650px; height: 400px; margin: 0 auto"></div>
            <div id="tooltip"></div>
        </form>
    </body>
</html>

Para continuar, agregamos un archivo PHP llamado "flotcharts-lineas.php", con el siguiente código:

<?php

include("FlotCharts.php");
//establecer zona horaria
date_default_timezone_set("America/Mexico_City");
//Crear una instancia de PieChart
$chart = new PieChart();
//Inicializar las Series
$chart->series = array();

$serie = new Serie();
$serie->label = "Abarrotes";
$serie->color = "#FF0000";
$serie->data = array();
array_push($serie->data, array(strtotime("2017-01-01 UTC") * 1000, 2300.85));
array_push($serie->data, array(strtotime("2017-01-02 UTC") * 1000, 2500));
array_push($serie->data, array(strtotime("2017-01-03 UTC") * 1000, 800));
array_push($serie->data, array(strtotime("2017-01-04 UTC") * 1000, 0));

array_push($chart->series, $serie);

//Generar Json
echo json_encode($chart);
?>

Finalmente, así queda nuestra gráfica:

No hay comentarios:

Publicar un comentario