DotNetCurry Logo

Using D3.js and ASP.NET Web API to design Pie Chart and Donut Chart

Posted by: Pravinkumar Dabade , on 11/11/2014, in Category ASP.NET
Views: 55683
Abstract: In this article, we will design a Pie chart and Donut chart using D3.js by fetching the data using ASP.NET Web API.

D3.js stands for Data-Driven Document. It is a JavaScript library using which we can manipulate documents based on data. The data can be fetched using multiple ways like Web Services, WCF Services, REST APIs or the relatively new Microsoft ASP.NET Web API amongst many others. Using D3, you can bind the data to the Document Object Model (DOM) and present that data with rich visualizations. D3 internally makes use of CSS, HTML and SVG capabilities to make your data presentable. It is powerful, fast and supports large datasets and dynamic behaviors for interactions and powerful and smooth animations.

D3.js provides easy and declarative selections of DOM nodes using W3C Selector APIs. D3 Selector APIs provides number of methods to manipulate nodes. For example –

  • Setting attributes and applying rich styles
  • Registering Event Listeners
  • You can add, remove and sort DOM nodes
  • You can change the HTML or the text contents of HTML elements
  • You can also have a direct selection/access to the DOM as each selection is an array of nodes

 

Likewise, we have various features of D3.js selectors which we can use to present data to our DOM nodes.

A simple selector example is the following:

var bodySelection = d3.select('body').style('background-color', 'blue');

In the above example, we are selecting body and changing its background color to blue. Another example would be as follows:

var divSelection = d3.selectAll('div').style('background-color', 'yellow');

In the above example, we are selecting all divs and changing its background color to yellow. If you are familiar with jQuery, the syntax looks similar to jQuery selectors or HTML5 Selectors.

D3 allows us to bind the data to the DOM elements and their attributes using a Data method which takes an array. For example:

d3.selectAll("div")
  .data([200,300,400,100])
  .style("height", function (data) { return data + "px"; });

In the above example, we are selecting all the div’s on the page and based on the index, the first value of an array will be passed to first div, second value to second div and so on.

In D3, you can also make use of Enter and Exit selector methods to create new nodes for incoming data, and remove outing nodes that are no longer used.

You can also apply transitions to nodes using D3. For example –

var area = d3.select('body')
            .append('svg')
            .attr('width', 500)
            .attr('height', 500);

var circle = area.append('rect')
                 .attr('width', 100)
                 .attr('height', 100)
                 .attr('fill', 'red');

circle.transition()
      .duration(2000)
      .delay(2000)
      .attr('width', 400)
      .each('start', function () { 
            d3.select(this).attr('fill', 'green');})
      .transition()
      .duration(2000)
      .attr('height', 400)
      .transition()
      .duration(2000)
      .attr('width', 50)
      .transition()
      .duration(2000)
      .attr('height', 50)
      .each('end', function () { 
            d3.select(this).attr('fill', 'blue'); });

In the above example, we are drawing a Rectangle and applying the transition to the same. Likewise, we can make use of various features of D3.js to present our data using rich visualizations.

A Quick overview of ASP.NET Web API

REST(REpresentational State Transfer) has emerged as the prominent way to create web services. By using REST we can build loose coupled services with data available on the web over HTTP protocol.

ASP.NET Web API is a platform for building RESTful applications. ASP.NET Web API is a framework using which we can build HTTP Services which can be called from a broad range of clients, browsers and mobile devices. ASP.NET Web API is the defacto standard of creating web services and replaces WCF.

When we think about exposing data on the web, we usually talk about four common operations which we use on a daily basis in our apps – CREATE, RETRIVE, UPDATE, DELETE.

We call these operations as CRUD operations. REST provides 4 basic HTTP verbs which we can map to our CRUD operations as described here - POST – CREATE, GET – RETRIVE, PUT – UPDATE, DELETE – DELETE.

By using REST, if you can connect to the web, any application can consume your data. When the data is pulled or pushed by using REST, the data is always serialized into or de-serialized from JSON or XML.

Setting up the application and ASP.NET Web API

To start designing the Pie chart and Donut chart, use the following tools and technologies:

  • Microsoft Visual Studio 2013 (Express or Professional)
  • Microsoft SQL Server 2012 (Express or Developer)
  • jQuery
  • D3.js
  • ASP.NET WEB API

Let’s first design the table where we can add our data. To design the table, open SQL Server Management Studio and write the following script:

CREATE TABLE [dbo].[CityPopulationTable](
    [CityID] [int] IDENTITY PRIMARY KEY,
    [CityName] [nvarchar](30) NULL,
    [Population] [int] NULL
)

Now insert some dummy data in this table as shown below: 

tabledata

Create an ASP.NET Web application by choosing Web Forms template. Then add the Entity Framework, jQuery and D3.js libraries into our web application using NuGet.

Once you add these libraries, right click on the Models folder in our Web application under Solution Explorer, and click on Add New Item. Choose Data  > ADO.NET Entity Data Model as shown below:

edm

Using Entity Data Model Wizard, connect to our database and choose CityPopulationTable. The Entity Data Model is shown here:

edmx

It’s time to implement the ASP.NET Web API into our project. Right click the web application and add a new folder with the name Controllers. Add a new Controller in this folder:

addwebapi

After adding the Web API, open Global.asax file and import two namespaces as shown here:

using System.Web.Http;
using System.Web.Routing;

Also add the following code to the Application_Start method –

GlobalConfiguration.Configure(WebApiConfig.Register);

The above line registers the Web API route in our web application. Now under App_Start folder, you will find WebApiConfig.cs file. Open this file and write the following code:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.Remove(config.Formatters.XmlFormatter);
}

In the above code, we are configuring Web API to make use of JSON formatter with camel casing, as most of the JavaScript developer will expect JSON output in Camel casing.

Now modify the Get method of our Web API controller as shown here:

public class PieChartController : ApiController
{
    NorthwindEntities dataContext = new NorthwindEntities();
    // GET api/piechart
    public IEnumerable<CityPopulationTable> Get()
    {
        return dataContext.CityPopulationTables.ToList();
    }
}

In the above code, we have created an object of our Entity Data model which will give access to the tables. Then we are returning an IEnumerable of our object CityPopulationTables.

To test our Web API, we will make use of a browser:

webapioutout

Let us design our Pie chart and Donut chart using the Web API data shown in above:

Creating D3 Charts

Add a HTML page with the name ‘CityPolulationPieChart.html’. Once you add the page, we will reference the jQuery and D3.js file in the page:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Pie Chart Example</title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/d3.js"></script>
</head>

We will make use of jQuery AJAX function to fetch the data from our Web API and display it in a Pie and Donut chart. Let’s add a DOM ready function into our <body> tag. In this function, we will first declare two arrays. First array will hold the data for our chart and the second array will hold the colors which we will use for our chart:

$(function () {
            var chartData = [];
            var colors = [];
});

In the next step, we will fetch the data from our Web API using jQuery $.ajax function. Add this code after our array declaration:

$.ajax({
        type: "GET",
        url: "api/PieChart",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            $.each(result, function (i,j) {
                chartData.push(j.population);
                var currentColor = '#' + Math.floor(Math.random() * j.population+5566656).toString(16);
                colors.push(currentColor);
            });
            console.log(chartData);}
        error: function (msg) {
            $("#result").text(msg);
        }
});

Note: Although I have used success and error here for devs using an older version of jQuery, these methods have been deprecated from jQuery 1.8. You should replace them with .done() and fail().

In the above code, we are using a GET request with the Web API URL and the type of data set to JSON. On successful completion of the request, we are running a loop using $.each() which will push the fetched data into our chartData array. We are also generating colors and adding them into our colors array.

Now it’s time to use the D3 selector. We will use D3 selector to select the body and will append the SVG element to the same by setting its height and width. Add this code after console.log function. The code is shown below –

var radius = 300;
var colorScale = d3.scale.ordinal().range(colors);
                    
var area = d3.select('body').append('svg')
             .attr('width', 1500)
             .attr('height', 1500);

Also note that we are using the scale function of D3 which allows us to set the ordinal scale with the range to set the scale’s output range. We have also added a variable called radius which is set to 300.

The next step is to group the elements and draw an arc into our SVG as shown in the following code:

var pieGroup = area.append('g').attr('transform', 'translate(300, 300)');
var arc = d3.svg.arc()
                .innerRadius(0)
                .outerRadius(radius);

In the above code, we are using radius variable as the outer radius and fixing the inner radius to 0. As the next step, use a pie layout available under D3. Then pass the chart data and append it to our group ‘g’. The code is shown below –

var pie = d3.layout.pie()
       .value(function (data) { return data; })
var arcs = pieGroup.selectAll('.arc')
       .data(pie(chartData))
       .enter()
       .append('g')
       .attr('class', 'arc');

Also observe, we are using D3 selector to select arc class added at the end, which will select all the elements which has a class arc. In the last step,  append the path and fill the color from our array. We will also display the population data as text to our pie chart. The code is shown below –

arcs.append('path')
    .attr('d', arc)
    .attr('fill', function (d) { return colorScale(d.data); });

arcs.append('text')
    .attr('transform', function (data) { return 'translate(' + arc.centroid(data) + ')'; })
    .attr('text-anchor', 'middle')
    .attr('font-size', '1em')
    .text(function (data) { return data.data; });

Now save your changes and run the page. You will see the output of our Pie chart as shown here:

piechart

Donut Chart

Designing a Donut chart is very simple. Just change the inner radius to something higher than zero. I am making it 200. The code is as shown here:

var arc = d3.svg.arc()
        .innerRadius(200)
        .outerRadius(radius);

This will render the Donut chart:

 

doughnutchart

Conclusion

In this article, we have seen how to create a Pie chart and a Donut chart using D3.js. We have used ASP.NET Web API and Entity Framework to fetch the data from SQL Server table and present the data in our chart.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Anthony Murphy on Monday, November 24, 2014 5:57 PM
Nice!!!! I will be able to use this..
Comment posted by jhh on Friday, February 13, 2015 5:55 AM
jh
Comment posted by Ilana on Tuesday, May 5, 2015 4:07 PM
I tried to implement it in my Visual studio ASP.net MVC internet project but it doesn't work. Can you please help me to figure out what exactly wrong.
Comment posted by Ilana on Wednesday, May 6, 2015 7:06 AM
I tried to implement it in my Visual studio ASP.net MVC internet project but it doesn't work. Can you please help me to figure out what exactly wrong.
Comment posted by Sv on Wednesday, May 6, 2015 8:50 AM
What is NorthwindEntities dataContext = new NorthwindEntities(); in API controller? Mine cannot find it. It says: the type or namespace could not be found.
Thank you.
Comment posted by Sv on Wednesday, May 6, 2015 10:11 AM
What is NorthwindEntities dataContext = new NorthwindEntities(); in API controller? Mine cannot find it. It says: the type or namespace could not be found.
Thank you.
Comment posted by Ilana on Wednesday, May 6, 2015 3:27 PM
I made it work. Great post. Thank you very much!!!