Creating a D3.js Pie Chart

Explains how to create a basic pie chart in D3.

Example program

View code

Example code

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>D3 Pie Chart</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>

<body>
  <script>
  // 1. Prepare data
  var dataset = [
    { "name": "A", "value": 5 },
    { "name": "B", "value": 6 },
    { "name": "C", "value": 8 },
    { "name": "D", "value": 1 },
    { "name": "E", "value": 2 },
    { "name": "F", "value": 6 },
    { "name": "G", "value": 8 },
    { "name": "H", "value": 6 },
    { "name": "I", "value": 10 },
    { "name": "J", "value": 9 }
  ]

  var width = 400; // Graph width
  var height = 300; // Graph height
  var radius = Math.min(width, height) / 2 - 10;

  // 2. Set SVG area
  var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);

  var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

  // 3. Set colors
  var color = d3.scaleOrdinal()
    .range(["#DC3912", "#3366CC", "#109618", "#FF9900", "#990099"]);

  // 4. Set function for pie chart dataset
  var pie = d3.pie()
    .value(function(d) { return d.value; })
    .sort(null);

  // 5. Set pie chart SVG elements
  var pieGroup = g.selectAll(".pie")
    .data(pie(dataset))
    .enter()
    .append("g")
    .attr("class", "pie");

  arc = d3.arc()
    .outerRadius(radius)
    .innerRadius(0);

  pieGroup.append("path")
    .attr("d", arc)
    .attr("fill", function(d) { return color(d.index) })
    .attr("opacity", 0.75)
    .attr("stroke", "white");

  // 6. Set pie chart text SVG elements
  var text = d3.arc()
    .outerRadius(radius - 30)
    .innerRadius(radius - 30);

  pieGroup.append("text")
    .attr("fill", "black")
    .attr("transform", function(d) { return "translate(" + text.centroid(d) + ")"; })
    .attr("dy", "5px")
    .attr("font", "10px")
    .attr("text-anchor", "middle")
    .text(function(d) { return d.data.name; });
  </script>
</body>

</html>

Example code explanation

1. Prepare data

Prepare the data for drawing the pie chart. Set the radius of the pie chart using JavaScript’s standard Math.min function.

var radius = Math.min(width, height) / 2 - 10;

2. Set SVG area

Set the SVG display area for showing the pie chart. Because a pie chart is basically drawn around the origin point 0,0, move it to the center of the screen.

var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

Set a <g> element and place the SVG elements of the pie chart inside it.

3. Set colors

Set the color scale for drawing the pie chart using the D3 method d3.scaleOrdinal.

var color = d3.scaleOrdinal()
  .range(["#DC3912", "#3366CC", "#109618", "#FF9900", "#990099"]);

d3.scaleOrdinal sets a function that repeatedly calls the array set by range. This time, a function that calls five colors is set as color and used.

4. Set function for pie chart dataset

Set a function that converts the provided dataset into pie chart data using D3’s d3.pie method.

var pie = d3.pie()
  .value(function(d) { return d.value; })
  .sort(null);

When the data set is passed to the configured function, pie(dataset), the converted data is output.
.value sets the value that determines the size of each pie slice. .sort(null) configures the data so that it is not reordered. .sort() is optional; if omitted, data is sorted by descending value.

After conversion, the data becomes an array of objects with the following values.

Value Description
data Reference to the original data
value Value of the pie chart element
index Index of the pie chart element, after sorting
startAngle Start angle of the arc
endAngle End angle of the arc
padAngle Gap angle between elements

5. Set pie chart SVG elements

Set the data using the configured pie function.

  var pieGroup = g.selectAll(".pie")
    .data(pie(dataset))
    .enter()
    .append("g")
    .attr("class", "pie");

Before starting, set a "g" element and place the pie slice ("path" element) and text ("text" element) inside it.

Set the function that configures the "d" attribute of the pie chart slice "path" element using D3’s d3.arc() method.

  arc = d3.arc()
    .outerRadius(radius)
    .innerRadius(0);

  pieGroup.append("path")
    .attr("d", arc)
    .attr("fill", function(d) { return color(d.index) })
    .attr("opacity", 0.75)
    .attr("stroke", "white");

d3.arc() sets the outer radius with .outerRadius(..) and the inner radius with .innerRadius(..). For example, set a value other than 0 in .innerRadius(..).

  arc = d3.arc()
    .outerRadius(radius)
    .innerRadius(85);

Then you can create a donut chart as shown below.

6. Set pie chart text SVG elements

Set the label text.

  var text = d3.arc()
    .outerRadius(radius - 30)
    .innerRadius(radius - 30);

  pieGroup.append("text")
    .attr("fill", "black")
    .attr("transform", function(d) { return "translate(" + text.centroid(d) + ")"; })
    .attr("dy", "5px")
    .attr("font", "10px")
    .attr("text-anchor", "middle")
    .text(function(d) { return d.data.name; });

Call d3.arc() again and set the method on text for text placement.
If the data converted for the pie chart is inserted into the .centroid(..) method, text can be placed at the center position in the radial direction of the pie chart.
Because the slice .innerRadius(..) is set to 0, this calls a new method to display the text slightly outside the center.
For the donut chart shown earlier, text is easier to read when placed in the center position, so there is no need to call d3.arc for displaying text. If you change text.centroid(d) to arc.centroid(d), it can be placed in the center as in the previous example.