Flotcharts con ASP.Net (Gráfica de Barras Múltiples)

Hola tyros!

Hoy les voy a mostrar como crear una gráfica de múltiples barras (agrupadas) con Flotcharts y ASP.Net.

Como ya hemos hecho costumbre, necesitamos una clase. Así que agregaremos un espacio de nombres llamado "FlotCharts" con una clase llamada "BarChart", con el siguiente código:

using System.Collections.Generic;
/// <summary>
/// Descripción breve de FlotCharts
/// </summary>
namespace FlotCharts
{
    public class BarChart
    {
        public object[] categories;
        public List<Serie> series = new List<Serie>();
        public struct Serie
        {
            public string label;
            public string color;
            public List<double[]> data;
        }
    }
}

Ahora agregaremos una página ASP.Net llamada "barras-multiples.aspx", con el siguiente código:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="barras-multiples.aspx.cs" Inherits="flotcharts_barras_multiples" %>

<!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="http://www.jqueryflottutorial.com/js/flot/jquery.flot.axislabels.js"></script>
    <script type="text/javascript" src="http://www.pikemere.co.uk/blog/js/jquery.flot.orderBars.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: "barras-multiples.aspx/GraficaBarras",
                dataType: "json",
                contentType: 'application/json',
                async: false,
                success: function (result) {
                    var options = {
                        series: {
                            bars: {
                                show: true,
                                align: "center",
                                barWidth: 0.1,
                                order: 1
                            }
                        },
                        xaxis: {
                            ticks: JSON.parse(result.d).categories,
                            autoscaleMargin: .10,
                            axisLabel: 'Meses del año'
                        },
                        yaxis: {
                            axisLabel: "Total"
                        },
                        legend: {
                            show: true
                        },
                        grid: {
                            hoverable: true,
                            clickable: true
                        }
                    };
                    var data = JSON.parse(result.d).series;
                    $.plot($("#bar-chart"), data, options);
                    //Configurar tooltip
                    $("#bar-chart").bind("plothover", function (event, pos, item) {
                        if (item) {
                            var x = item.datapoint[0].toFixed(2),
                                y = item.datapoint[1].toFixed(2);
                            //Obtener fecha
                            $("#tooltip").html("<b>" + item.series.label + "</b> = " + 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="bar-chart" style="width: 650px; height: 400px; margin: 0 auto"></div>
        <div id="tooltip"></div>
    </form>
</body>
</html>

Con el siguiente código C#:

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

    }
    [WebMethod]
    public static string GraficaBarras()
    {
        BarChart chart = new BarChart();
        chart.categories = new object[]{
            new object[]{ 0,"Enero"},
            new object[]{ 1,"Febrero"}
        };
        //Agregar Datos
        chart.series.Add(new BarChart.Serie()
        {
            label = "Fresas",
            color = "#FF0000",
            data = new List<double[]>() {
                new double[] { 0, 20 } ,
                new double[] { 1, 12 }
            }
        });
        chart.series.Add(new BarChart.Serie()
        {
            label = "Manzanas",
            color = "#00CC00",
            data = new List<double[]>() {
                new double[] { 0, 5 },
                new double[] { 1, 21 }
            }
        });
        chart.series.Add(new BarChart.Serie()
        {
            label = "Uvas",
            color = "#9900CC",
            data = new List<double[]>() {
                new double[] { 0, 13 },
                new double[] { 1, 12 }
            }
        });
        //Generar Json
        return new JavaScriptSerializer().Serialize(chart);
    }
}

Finalmente, así queda nuestra gráfica:

No hay comentarios:

Publicar un comentario