Create a simple Donut Chart using D3.js

We will learn how to Create a simple Donut Chart using D3.js . Even though the Pie chart is not very efficient in data visualization the Donut Charts are sometimes very helpful. We have learned how to Create a Simple Pie Chart using D3.js in our previous post.

In this article we will take our basic pie chart and convert that to a donut chart. We will also add the legends and animate the Donut Chart using attrTween function.

We will use the below dataset to create our Donut Chart.

1

2

3

4

5

6

7

vardataset=[

{name:'IE',percent:39.10},

{name:'Chrome',percent:32.51},

{name:'Safari',percent:13.68},

{name:'Firefox',percent:8.71},

{name:'Others',percent:6.01}

];

Now create the basic chart using following code. We will use the padAngle() function to add the padding to the Pie layout.This time we will use the d3.scale.category10() function for the color scale.We will also set the innerRadius() to the arc to create the Donut Chart instead of the Pie Chart.

Now we will use the the attrTween() function to animate the chart. We will use the d3.interpolate() method to calculate the intermidiate steps. The transition duration has been set to 1s. Add the following code, refresh the html. You can see the chart is now animating nicely.

JavaScript

1

2

3

4

5

6

7

8

path.transition()

.duration(1000)

.attrTween('d',function(d){

varinterpolate=d3.interpolate({startAngle:0,endAngle:0},d);

returnfunction(t){

returnarc(interpolate(t));

};

});

The Next step is to add the legends once the animation has been completed. We will use the setTimeout() function to create our legends after 1sec so that it will be added after the transition has been completed.

At first we will add the percentage at the center of the arc, which is similar to the previous chart we created. This time we will also animate the text. Here is the code.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

vartext=svg.selectAll('text')

.data(pie(dataset))

.enter()

.append("text")

.transition()

.duration(200)

.attr("transform",function(d){

return"translate("+arc.centroid(d)+")";

})

.attr("dy",".4em")

.attr("text-anchor","middle")

.text(function(d){

returnd.data.percent+"%";

})

.style({

fill:'#fff',

'font-size':'10px'

});

In order to add the legends we will draw a text and a rectangle. We will add a group and then add the text and the rect to the group. The position of the group is calculated dynamically. We will pass the color.domain() in the data() function.

Thanks for this great example. It looks really cool! I’m trying to implement it but it’s giving me some errors. It says “path” is null just before the transition part. Would you please be able to help? Thank you so much. I’ll be happy to share my email address with you.