Challenge: Draw a Donut Chart
Explore how to draw a donut chart using D3.js by applying the d3.arc and d3.pie methods. This lesson helps you practice implementing chart fundamentals by converting data into a visually appealing donut shape with specified inner and outer radii. You will strengthen your skills in SVG drawing and pie chart creation within D3.
We'll cover the following...
We'll cover the following...
Problem statement
Draw a donut chart of (outerRadius=150) and (innerRadius=50) for given data using the concept of a pie chart. Use the d3.arc() and d3.pie APIs to draw the donut chart.
Given data
var margin = {top: 20, right: 20, bottom: 60, left: 80},
width = 500 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body") //create Svg element
.append("svg")
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.style("border", "solid 1px red")
.attr("transform","translate(210,0)"); // To align svg at the center in the output tab.
var chart=svg.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
var data = [
{language: "Python", value: 30},
{language: "Java", value: 20},
{language: "C/C++", value: 15},
{language: "Javascript", value: 35},
{language: "PHP", value: 15},
];
Expected output
Coding exercise
The problem is designed to check your understanding, so you are encouraged to solve it on your own. If you are completely stuck, then refer to the next lesson which will explain the solution in detail.
If you’re stuck, click the “Show Solution” button.