Creating a Pie Chart with D3: A Comprehensive Tutorial

Master the art of creating pie charts using D3.js with our detailed tutorial. Learn about essential D3 methods and step-by-step instructions for building dynamic visualizations.



Creating a Pie Chart Using D3

In this chapter, we’ll learn how to create pie charts using D3.js. We’ll use various D3 methods to build our pie chart visualization.

D3 Methods

D3 Method Description
SVG Path Creates a path in SVG from defined commands.
d3.scaleOrdinal() Creates an ordinal scale.
d3.pie() Creates a pie generator.
d3.arc() Creates an arc generator.

SVG Path

A path element is used to draw paths in SVG. It takes commands to define how the path is drawn.


<body>
<svg height="210" width="400">
<path d="M150 0 L75 200 L225 200 Z" />
</svg>
</body>

This code draws a triangular path starting from (150,0), creating lines to (75,200) and (225,200), and then back to (150,0).

d3.scaleOrdinal()

The d3.scaleOrdinal() method creates an ordinal scale, where the order is important, but not the difference.

Syntax

<body>
<script>
var color = d3.scaleOrdinal(['#4daf4a','#377eb8','#ff7f00','#984ea3','#e41a1c']);
console.log(color(0)); // #4daf4a
console.log(color(1)); // #377eb8
console.log(color(2)); // #ff7f00
console.log(color(3)); // #984ea3
console.log(color(4)); // #e41a1c
console.log(color(5)); // #4daf4a (restarts from 0)
</script>
</body>

The color function maps index values to the specified colors. If an index exceeds the range, it restarts from the beginning.

d3.pie()

The d3.pie() function generates data for creating a pie chart, including start and end angles for each wedge.

Syntax

<script>
var data = [2, 4, 8, 10];
var pie = d3.pie();
console.log(pie(data));
</script>

This code calculates start and end angles for each slice based on the input data.

d3.arc()

The d3.arc() function creates arcs used for pie chart wedges. The innerRadius defines the radius of the inner circle (0 for pie charts, greater than 0 for donut charts).

Example: Pie Chart

Here’s how to create a simple pie chart:

Syntax

<body>
<svg width="300" height="200"></svg>
<script>
var data = [2, 4, 8, 10];
var svg = d3.select("svg"),
width = svg.attr("width"),
height = svg.attr("height"),
radius = Math.min(width, height) / 2,
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var color = d3.scaleOrdinal(['#4daf4a','#377eb8','#ff7f00','#984ea3','#e41a1c']);
var pie = d3.pie();
var arc = d3.arc().innerRadius(0).outerRadius(radius);

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

arcs.append("path")
.attr("fill", function(d, i) {
    return color(i);
})
.attr("d", arc);
</script>
</body>

Explanation:

  • Variables Initialization: Define SVG dimensions and radius.
  • Group Element: Create a group element centered within the SVG.
  • Color Scale: Define colors for the chart slices.
  • Pie and Arc Generators: Set up pie and arc generators.
  • Arcs and Paths: Append path elements for each slice and color them.

Example: Pie Chart with External CSV Data

To use data from an external CSV file:


<!DOCTYPE html>
<html>
<head>
<style>
.arc text { font: 10px sans-serif; text-anchor: middle; }
.arc path { stroke: #fff; }
.title { fill: teal; font-weight: bold; }
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<svg width="500" height="400"></svg>
<script>
var svg = d3.select("svg"),
    width = svg.attr("width"),
    height = svg.attr("height"),
    radius = Math.min(width, height) / 2,
    g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
    color = d3.scaleOrdinal(['#4daf4a','#377eb8','#ff7f00','#984ea3','#e41a1c']),
    pie = d3.pie().value(function(d) { return d.percent; }),
    path = d3.arc().outerRadius(radius - 10).innerRadius(0),
    label = d3.arc().outerRadius(radius).innerRadius(radius - 80);

d3.csv("browseruse.csv", function(error, data) {
    if (error) throw error;

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

    arc.append("path")
        .attr("d", path)
        .attr("fill", function(d) { return color(d.data.browser); });

    arc.append("text")
        .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
        .text(function(d) { return d.data.browser; });

    svg.append("g")
        .attr("transform", "translate(" + (width / 2 - 120) + "," + 20 + ")")
        .append("text")
        .text("Browser use statistics - Jan 2017")
        .attr("class", "title");
});
</script>
</body>
</html>

Explanation:

  • CSV Data: Load browser usage statistics from a CSV file.
  • Arc and Label Generators: Define arcs for the pie slices and labels.
  • Data Binding: Bind data to pie chart slices and append text labels.
  • Title: Add a title to the chart.

Donut Chart

To convert the pie chart into a donut chart, adjust the innerRadius of the arc:

Syntax

var arc = d3.arc().outerRadius(radius).innerRadius(100);

This change creates a donut chart with a hole in the center.