In this section, we will learn how to create pie charts using D3.js. Pie charts are a great way to visualize proportions and percentages in a dataset. We will cover the following topics:

  1. Understanding Pie Charts
  2. Setting Up the Pie Chart
  3. Creating the Pie Layout
  4. Drawing the Pie Slices
  5. Adding Labels
  6. Styling the Pie Chart
  7. Practical Exercise

  1. Understanding Pie Charts

A pie chart is a circular statistical graphic divided into slices to illustrate numerical proportions. Each slice represents a category's contribution to the whole.

  1. Setting Up the Pie Chart

First, let's set up our environment and create the basic structure for our pie chart.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pie Chart with D3.js</title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <style>
        .slice {
            stroke: #fff;
            stroke-width: 2px;
        }
    </style>
</head>
<body>
    <svg width="500" height="500"></svg>
    <script src="pie-chart.js"></script>
</body>
</html>

JavaScript Setup

Create a file named pie-chart.js and start by defining the dimensions and creating an SVG container.

const width = 500;
const height = 500;
const radius = Math.min(width, height) / 2;

const svg = d3.select("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", `translate(${width / 2}, ${height / 2})`);

  1. Creating the Pie Layout

D3.js provides a d3.pie function to create a pie layout. This function will compute the start and end angles for each slice.

const data = [10, 20, 30, 40, 50];

const pie = d3.pie();

const arcs = pie(data);

  1. Drawing the Pie Slices

To draw the pie slices, we use the d3.arc function, which generates the path data for each slice.

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

svg.selectAll("path")
    .data(arcs)
    .enter()
    .append("path")
    .attr("class", "slice")
    .attr("d", arc)
    .attr("fill", (d, i) => d3.schemeCategory10[i]);

  1. Adding Labels

Labels can be added to each slice to indicate the value or category.

svg.selectAll("text")
    .data(arcs)
    .enter()
    .append("text")
    .attr("transform", d => `translate(${arc.centroid(d)})`)
    .attr("text-anchor", "middle")
    .text(d => d.data);

  1. Styling the Pie Chart

You can style the pie chart using CSS. For example, you can add a stroke to each slice to separate them visually.

.slice {
    stroke: #fff;
    stroke-width: 2px;
}

  1. Practical Exercise

Exercise: Create a Pie Chart with Custom Data

Objective: Create a pie chart using a custom dataset and add labels to each slice.

Dataset:

const data = [
    { label: "A", value: 30 },
    { label: "B", value: 70 },
    { label: "C", value: 45 },
    { label: "D", value: 85 },
    { label: "E", value: 50 }
];

Steps:

  1. Modify the data array to use objects with label and value properties.
  2. Update the pie function to use the value property.
  3. Add labels using the label property.

Solution:

const data = [
    { label: "A", value: 30 },
    { label: "B", value: 70 },
    { label: "C", value: 45 },
    { label: "D", value: 85 },
    { label: "E", value: 50 }
];

const pie = d3.pie()
    .value(d => d.value);

const arcs = pie(data);

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

svg.selectAll("path")
    .data(arcs)
    .enter()
    .append("path")
    .attr("class", "slice")
    .attr("d", arc)
    .attr("fill", (d, i) => d3.schemeCategory10[i]);

svg.selectAll("text")
    .data(arcs)
    .enter()
    .append("text")
    .attr("transform", d => `translate(${arc.centroid(d)})`)
    .attr("text-anchor", "middle")
    .text(d => d.data.label);

Conclusion

In this section, we learned how to create a pie chart using D3.js. We covered setting up the environment, creating the pie layout, drawing the slices, adding labels, and styling the chart. We also provided a practical exercise to reinforce the concepts learned. In the next section, we will explore creating scatter plots.

© Copyright 2024. All rights reserved