Google Charts con ASP.NET (Gráfica de Lineas Múltiples)

Hola tyros, yo de nuevo, esta vez para mostrarles como crear una gráfica de Líneas.

Para este ejercicio utilizaremos la clase "Charts", expuesta en el ejercicio anterior, este es el código:


using System.Collections.Generic;
public class Charts
{
    public List<ChartColumn> cols = new List<ChartColumn>();
    public List<ChartRow> rows = new List<ChartRow>();
    public struct ChartColumn
    {
        public string id;
        public string label;
        public string pattern;
        public string type;
        public string role;
    }
    public struct ChartRow
    {
        public List c;
    }
    public struct ChartRowValue
    {
        public object v;
        public object f;
    }
    public void AddColumn(ChartColumn col) { cols.Add(col); }
    public void AddRow(ChartRow row) { rows.Add(row); }
}


Esta clase nos servirá para poder generar el JSon estandar que requieren las gráficas de Google.

Luego, en nuestro archivo "lineas.aspx", ponemos el siguiente código:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="lineas.aspx.cs" Inherits="lineas" %>
<!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 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() {
            //Lineas
            $.ajax({
                type: 'POST',
                url: "lineas.aspx/GraficaLineas",
                dataType: "json",
                contentType: 'application/json',
                async: false,
                success: function (result) {
                    var data = new google.visualization.DataTable(result.d);
                    var options = {
                        title: '',
                        hAxis: {
                            title: 'Fecha'
                        },
                        vAxis: {
                            title: 'Total'
                        },
                        pointSize: 5,
                        backgroundColor: { fill: 'transparent' },
                        'height': 300
                    };
                    target = document.getElementById('line-chart');
                    var chart = new google.visualization.LineChart(target);
                    chart.draw(data, options);
                }
            });

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



Por último, el código C#:


using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.Services;
public partial class lineas : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static string GraficaLineas()
    {
        GoogleCharts chart = new GoogleCharts();
        //Agregar columnas
        chart.cols.Add(new GoogleCharts.ChartColumn()
        {
            id = "",
            label = "Fecha",
            pattern = "",
            type = "string"
        });//col1
        chart.cols.Add(new GoogleCharts.ChartColumn()
        {
            id = "",
            label = "Abarrotes",
            pattern = "",
            type = "number"
        });//col2
        chart.cols.Add(new GoogleCharts.ChartColumn()
        {
            role = "annotation",
            type = "string"
        });//col3, anotación para columna 2
        chart.cols.Add(new GoogleCharts.ChartColumn()
        {
            id = "",
            label = "Lácteos",
            pattern = "",
            type = "number"
        });//col4
        chart.cols.Add(new GoogleCharts.ChartColumn()
        {
            role = "annotation",
            type = "string"
        });//col5,  anotación para columna 4


        //Agregar rows
        chart.rows.Add( new GoogleCharts.ChartRow()
        {
                c = new List<GoogleCharts.ChartRowValue>()
                {
                    { new GoogleCharts.ChartRowValue() { v = "01/01/2017" } },
                    { new GoogleCharts.ChartRowValue() { v = 2300.85 } },
                    { new GoogleCharts.ChartRowValue() { v = 2300.85 } },
                    { new GoogleCharts.ChartRowValue() { v = 750 } },
                    { new GoogleCharts.ChartRowValue() { v = 750 } }
                }
            }
        );
        chart.rows.Add(new GoogleCharts.ChartRow()
        {
            c = new List<GoogleCharts.ChartRowValue>()
            {
                { new GoogleCharts.ChartRowValue() { v = "02/01/2017" } },
                { new GoogleCharts.ChartRowValue() { v = 2500 } },
                { new GoogleCharts.ChartRowValue() { v = 2500 } },
                { new GoogleCharts.ChartRowValue() { v = 1350 } },
                { new GoogleCharts.ChartRowValue() { v = 1350 } }
            }
        });
        chart.rows.Add(new GoogleCharts.ChartRow()
        {
            c = new List<GoogleCharts.ChartRowValue>()
            {
                { new GoogleCharts.ChartRowValue() { v = "03/01/2017" } },
                { new GoogleCharts.ChartRowValue() { v = 800 } },
                { new GoogleCharts.ChartRowValue() { v = 800 } },
                { new GoogleCharts.ChartRowValue() { v = 2500 } },
                { new GoogleCharts.ChartRowValue() { v = 2500 } }
            }
        });
        chart.rows.Add(new GoogleCharts.ChartRow()
        {
            c = new List<GoogleCharts.ChartRowValue>()
            {
                { new GoogleCharts.ChartRowValue() { v = "04/01/2017" } },
                { new GoogleCharts.ChartRowValue() { v = 0 } },
                { new GoogleCharts.ChartRowValue() { v = 0 } },
                { new GoogleCharts.ChartRowValue() { v = 7000 } },
                { new GoogleCharts.ChartRowValue() { v = 7000 } }
            }
        });

        return new JavaScriptSerializer().Serialize(chart);

    }
}


Así se ve nuestra gráfica:

No hay comentarios:

Publicar un comentario