How to use D3.js for Server Side Chart Generation in .NET (Part 1)

After finally finishing my studies (for now), I am getting my "old life" back again! That means more time for coding, research and of course blogging. As one of my first (small?!) series that I will be writing will be about "How to use D3.js for Server Side Chart Generation in .NET" that will be splitted in few parts, so lets get started!

How to use D3.js for Server Side Chart Generation in .NET

Part 1: Creating a Donut Chart using D3.js
Part 2: Render/Export D3.js Chart as PNG Image using PhantomJS
Part 3: Creating a simple REST Service using ASP.NET Web API

First of all, we need a simple empty HTML Document that will be used later on as a Tamplate for our chart generation. It has do contain the D3.js logic for our Donut Chart and all other needed assets like CSS, Images etc.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
  position: relative;
  background-color: #FFF;
}
 
svg {
    width: 100%;
    height: 100%;
}
 
text {
    font-size: 15px;
    font-family: Arial;
}
</style> 
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<div id="chart"></div>
</body>

As you can see, we have defined few CSS global styles for Body, SVG, and Texts and the most important thing, we have included the latest minified D3.js version from their CDN and added a wrapper DIV with id=”chart” that will contain our generated chart.

Now we should define our dataset that we will be using for our chart generation:

var data = [{ label: 'Here', value: 190000, color: "#1e398f" },
            { label: 'Some', value: 50000, color: "#f7a600" },
            { label: 'Labels', value: 420000, color: "#e17e62" },
            { label: 'Needed', value: 1530000, color: "#985181" }];

I strongly suggest that you put all properties you will need in the dataset, so you don’t have to change anything in this Template HTML when you start using it from your ASP.NET Web Application later in this series.

Before we start implementing the chart logic, we should also put following variables that are needed for correct calculation of our donut:

var svg_width = 600;
var svg_height = 400;
/* Radius of the Donut should be a third of defined space */
var radius = Math.min(svg_width, svg_height) / 3;

Now we are all set to start writing the chart generation code! I will split it in two parts, first will be rendering of needed SVG and Layout elements and second will be rendering of our Donut slices. So first part should look like this:

var svg = d3.select("#chart")
        .attr("style", "width: " + svg_width + "px; height: " + svg_height + "px")
        .append("svg")
        .append("g")
 
    svg.append("g")
        .attr("class", "slices");
 
var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) {
        return d.value;
    });
 
var arc = d3.svg.arc()
    .outerRadius(radius)
    .innerRadius(radius * 0.5);
 
svg.attr("transform", "translate(" + svg_width / 2 + "," + svg_height / 2 + ")");

First we have extended our wrapper DIV with width and height styles, and appended a SVG element to it. In this SVG element we will render our Donut chart. Then we created a d3.js pie layout object and assigned a value property to return same named value property from our dataset (return d.value, where “d” is always assigned dataset for given object).

Next thing is to define an arc object with outerRadius and innerRadius. By defining the innerRadius we have actually created a Donut chart out of Pie chart by creating that hole in the middle of Pie that is half of our radius.

Last but not least, we want to position the chart in the middle of our wrapping div by calling the translate function with half of svg_width and svg_height as x,y position parameters.

Now, all we need to do is to generate the Donut/Pie slices in form of SVG Paths and interpolate it on our arc object that is already defined and centered in our wrapper DIV:

/* Render Pie Slices */
var slice = svg.select(".slices").selectAll("path.slice")
    .data(pie(data));
 
slice.enter()
    .insert("path")
    .style("fill", function(d) { return d.data.color; });
 
slice        
    .transition().duration(1000)
    .attrTween("d", function(d) {
        this._current = this._current || d;
        var interpolate = d3.interpolate(this._current, d);
        this._current = interpolate(0);
        return function(t) {
            return arc(interpolate(t));
        };
    })
 
slice.exit()
    .remove();

Here is where the whole “magic” happens, that is at least what I thought when I first started using D3.js!  In short words, we are assigning our dataset to a pie layout object and that object again in our .selectAll statement.
This .selectAll statement can be somehow hard to understand at the beginning but you will get used to it. Now we are going throughout every dataset entry and basically inserting a path element into our SVG with fill color value from our dataset property named color and in next step we are interpolating it on our arc element.

At the end, we should be able to see our new Donut chart by opening the HTML file in any Browser and it should be looking like on this Preview Page here.

In the next Part of this Series, I will be explaining how to Render/Export this SVG Chart as PNG Image file using PhantomJS.


Posted Jul 15 2015, 11:44 AM by Armin Kalajdzija
Filed under: , , ,

Comments

Armin Kalajdzija Posts wrote How to use D3.js for Server Side Chart Generation in .NET (Part 3)
on 07-30-2015 14:31

How to use D3.js for Server Side Chart Generation in .NET Part 1: Creating a Donut Chart using D3.js

Genevieve wrote re: How to use D3.js for Server Side Chart Generation in .NET (Part 1)
on 03-22-2016 12:20

Heck yeah this is exltacy what I needed.

developers.de is a .Net Community Blog powered by daenet GmbH.