Mayur Deore's Blog

Post info:

RGraph Class Library Nuget Package (1.0.0): 3D Pie Chart

This article gives steps for RGraph Class Library to create 3D Pie Chart in ASP .NET from dataset.

RGraph is free JavaScript Library for creating dynamic charts using HTML5 Canvas tag. For more information about features and examples go to RGraph Official Web-Site. In this article I’m going to introduce you to RGraph Class Library, which you can download from Nuget Package Manger. I’m going to use RGraph JavaScript library can be downloaded from here.

 

In many Web Applications there is need of presenting data summary in Pie Chart. Pie Chart allows us to analyse data using proportional sectors. In case of Simple Shop System Application, user can analyse per day sales of products in pie chart to determine the product in demand.

 

Let’s see simple example to create 3D Pie Chart using RGraph.

 

I have referenced some JavaScript files required for 3D pie graph as follows.

 

    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/RGraph/RGraph.common.core.js"></script>
    <script src="Scripts/RGraph/RGraph.common.dynamic.js"></script>
    <script src="Scripts/RGraph/RGraph.common.tooltips.js"></script>
    <script src="Scripts/RGraph/RGraph.pie.js"></script>
    

 

And in HTML created canvas element as:

 

 <canvas id="cvs" width="900" height="600"></canvas>

 

To draw 3D pie Chart javascript code is:

 

new RGraph.Pie({
                id: 'cvs', <!--canvas id-->
                data: [5,8,17,13],<!-- numeric values -->
                options: {
                    textAccessible:false, 
                    tooltips: ['AC','TV','Mobiles','Washing Machine'], 
                    labels: ['AC', 'TV', 'Mobiles', 'Washing Machine'], 
                    colors: ['Red','Blue','Green','Yellow'], 
                    variant: 'pie3d', 
                    labelsSticksList: true, 
                    labelsSticksColors: ['Red', 'Blue', 'Green', 'Yellow'], 
                    radius: 80, title: 'Today Sale' 
                 } 
    }).draw();

 

Short description of above code:

data:- represents numerical proportional of each slice of pie chart.

toolTips:- Represents the text displayed when user interact with slice e.g onclick.

labels:- Represents the descriptive name of the each slices of pie chart.

title:- Pie Chart title

For other field descriptions click here.

The output of above set up is:

 

piechart3drgraph2

 

In above example, I have provided hard code data in JavaScript code for pie chart. But in Web Applications, we can’t do that. The data is dynamic and most of the time (I mean always) provided by server. The data can be retrieved from database,excel or web service. In case of ASP .NET generally I create WebMethod which will return the list of strings for each data,labels and colors. Every time to draw chart I needed to create list of strings and send it to client for representation in Chart,so thought about creating class library instead of doing same coding again and again.

 

In RGraph Class Library I just need to provide dataset of 2 columns, first for labels and second for data(must be numeric),colors are auto generated by library. This dataset can be generated from database, excel file or any relational data. Let’s see how this library helps to avoids lots of coding for sending data from server to client and then draw 3D pie chart.

 

First install RGraph Javascript library from here. Then in Visual studio install RGraph Class Library using NuGet Package Manager.Run following command in Package Manager Console.

 

Install-Package RGraph.classLibrary

 

This will also create javascript file in Scripts folder having function for creating 3D pie Chart.

 

After installing above library next step is to create server side method which will return the data for Pie Chart. I have created WebMethod named getChartData which returns object of class Chart, availabe in RGraph namespace.

 

using System.Data;
using System.Web.Services;
using RGraph;//From RGraph Library

[WebMethod]
public static Chart getChartData()
{
            var returnData = new Chart();

            var dataset = new DataSet();

            var datatable = new DataTable();
            datatable.Columns.AddRange(new DataColumn[]{
                new DataColumn("Label",typeof(string)),
                new DataColumn("Value",typeof(double))}
        );
            var datarow = datatable.NewRow();

            datarow[0] = "PHP";
            datarow[1] = 100;
            datatable.Rows.Add(datarow);
            datarow = datatable.NewRow();
            datarow[0] = "Ruby";
            datarow[1] = 100;
            datatable.Rows.Add(datarow);
            datarow = datatable.NewRow();
            datarow[0] = "CSharp";
            datarow[1] = 100;
            datatable.Rows.Add(datarow);
            dataset.Tables.Add(datatable);

            var config = new GraphConfig();
            config.Colors = new string[] { "Red", "Green", "Blue" };
            var graph = new Graph(config);
            returnData = graph.getGraphData(dataset);
            return returnData;


}

 

In above code, dataset is populated with data manually, this dataset can be populated by data from dataset or  any other data source.

 

NOTE: First Column must contain label data and second column must contain numerical value.

 

The Pie class object will generate Pie Chart data from dataset and wrap that data in Chart class object. GraphConfig Class is provided in case you want custom colors, which is not compulsory. The WebMethod will return the Chart object which will be accessed in JavaScript code.

 

The JavaScript Code for AJAX call to the above WebMethod is.

 

        $(function () {

            $.ajax({

                url: "Default.aspx/getChartData",
                type:"post",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                   <!--4th parameter is boolean true for 3D and false for 2D-->
                    chartPieChart(result, 'cvs', 'Programming Languages',true);
                }
            });

        });

 

In above code snippet, chartPieChart is function in RGraph.custom.js created while installing RGraph Class Library.

 

This function is as follows (No need to write it,just reference RGraph.custom.js in web page,which already have this function):

var graphdata;
var chartData;
var labelData;
var colorData;
var opt;

function set()
{

  opt  =  {

    tooltips: labelData,
    labels: labelData,
    colors: colorData,
    textAccessible: false,
    gutterBottom:120,
    gutterTop: 120,
    gutterLeft: 120,
    gutterRight: 120



};
}

function chartPieChart(response, canvasId, graphTitle,flag) {

    /// <signature>
    /// <summary>Function to draw pie chart on given Canvas Id</summary>
    /// <param name="result">Data generated by RGraph class (generally response of webmethod)</param>
    /// <param name="canvasId" type="string">Canvas element Id</param>
    /// <param name="graphTitle" type="string">Graph Title</param>
    /// <param name="flag" type="boolean">Is 3d then True else False</param>
    /// </signature>
     graphdata = response.d;

     chartData = eval(graphdata.Data);
     labelData = eval(graphdata.Label);
     colorData = eval(graphdata.Color);

     set();
    if(flag)
        opt.variant = 'pie3d';

    opt.radius = 80;
   

    opt.title = graphTitle;
    var pie = new RGraph.Pie({
        id: canvasId,
        data: chartData,
        options:opt
    }).draw();
}

That’s it, now after running the web page the output will be:

 

 

piechart3drgraph1

 

Using same method we can create Line as well as Bar chart, just call corresponding method from Rgraph.custom.js after capturing data from webmethod. The RGraph Class Library project is on github.

Hope you liked this article. For any query/suggestions let me know about it by commenting below.

Mayur Deore

Facebook Twitter LinkedIn 

Leave a Reply

Your email address will not be published. Required fields are marked *