• Breaking News

    26 March 2016

    Google Visualization charts - Basic Bar chart with dynamic data



    Google is providing very powerful and easy understandable APIs to create good looking and useful Graph/Charts.  Good knowledge in JQuery will help us to understand the structure easily. Google is providing different kinds of Charts which we use often in our daily activities. We can find different kinds of Charts in Google gallery. Just by adding the related Chart API to our ASPX page(for DotNet developers) we can get the chart into our application.

    Now we will see how to bind data to a bar chart. If we go to google visualization chart page, we can find different charts and some information about customizing the charts. Of course its purely static data available there in HTML format. Now we will see how to bind dynamic data to the chart.

    Google Gallery Chart

    If you go to this link, you will find a graph there, with population of different cities in USA. As we already discussed,  its a static data. Now, let us see, how to generate the same graph with dynamic data.







    The database structure would be as below.
    City2010 Population
    New York City, NY8175000
    Los Angeles, CA3792000
    Chicago, IL2695000
    Houston, TX2099000
    Philadelphia, PA1526000


    Now I am going to show this data in Bar chart format using Google Visualization Charts feature.

    Create a table in SQL server as below


    CREATE TABLE Population
    (
    City VARCHAR(100),
    Population2010 FLOAT

    )


    Insert data into the table which is in the above table.


    Open a new DotNet web application and add new aspx page with name "BarGraph.aspx"

    Download latest JQuery (jquery-2.2.2.min.js) file from the below link "https://jquery.com/download/" and add the same to your application.


    <head runat="server">
        <title></title>
        <script src="jquery-2.2.2.min.js"></script>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
         <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['table']}]}"></script>
        <script type="text/javascript">

            function Displaygraph() {
                $.ajax({
                    type: "POST",
                    url: "BarGraph.aspx/getGraphData",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        drawchart(response.d);
                    },
                    failure: function (response) {
                        alert(response.d);
                    }
                });
            }

            google.charts.load('current', { packages: ['corechart', 'bar'] });
            google.charts.setOnLoadCallback(drawchart);
            function drawchart(dataValues) {        
                var data = new google.visualization.DataTable();           
                data.addColumn('string', 'City');
                data.addColumn('number', 'Population');
                for (var i = 0; i < dataValues.length; i++) {
                   data.addRow([dataValues[i].City, dataValues[i].Population]);
                }
                var options = {
                    title: 'Population of Largest U.S. Cities',
                    chartArea: { width: '50%' },
                    hAxis: {
                        title: 'Total Population',
                        minValue: 0
                    },
                    vAxis: {
                        title: 'City'
                    }
                };         
                var chart = new google.visualization.BarChart(document.getElementById('Inchart_div'));

                chart.draw(data, options);
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <input id="btnGraph" type="button" value="Show graph" onclick="Displaygraph()" />
                <div id="Inchart_div"></div>
            </div>
        </form>

    </body>

    Now go to code behind and add web method as below :


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    namespace GoogleGraph
    {
        public partial class BarGraph : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {

            }

            [System.Web.Services.WebMethod]
            public static population[] getGraphData()
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PopulationData"].ConnectionString);
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM Population", con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                DataTable dt = ds.Tables[0];
                List<population> popDetails = new List<population>();
                foreach (DataRow dtrow in dt.Rows)
                {
                    population details = new population();
                    details.City = dtrow["City"].ToString();
                    details.Population = Convert.ToDouble(dtrow["Population2010"]);
                    popDetails.Add(details);
                }

                return popDetails.ToArray();
            }
        }

        public class population
        {
            public string City { get; set; }
            public double Population { get; set; }
        }
    }



    Save,Build and run the application. You will get the graph in button click event as shown below


      



    We can customize the chart as we need. Will discuss the same in upcoming posts.


    No comments:

    Post a Comment

    Blogger Tips and TricksLatest Tips And TricksBlogger Tricks '; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();

    Fashion

    Popular

    Beauty

    Travel

    Comments