Chuck's Academy

Graphs with D3

Creating Pie and Donut Charts

Pie and donut charts are useful for visualizing proportions within a dataset. These charts divide a circle into segments that represent different categories. In this chapter, we will learn how to create pie and donut charts using D3.

Example Data

For this chapter, we will use a dataset representing different categories and their respective sizes:

javascript

Setting Up the SVG

First, we set up the SVG area where the pie or donut chart will be drawn:

javascript

Creating a Pie Chart

Arc Generator Setup

D3 provides an arc generator function that makes it easy to create arc segments based on data:

javascript

Pie Layout Generation

We use D3's pie function to calculate the arc values:

javascript

Drawing the Arcs

Now we draw the arc segments (pie slices):

javascript

Creating a Donut Chart

To create a donut chart, we simply adjust the inner radius in the arc generator:

javascript

Customizing Pie and Donut Charts

We can customize the pie or donut chart by adding labels to display categories or values:

javascript

Adding Interactivity

Let's add basic interactivity, such as a tooltip that shows the value when hovering over a segment:

javascript

Summary

In this chapter, we learned how to create pie and donut charts in D3. We started with the basic setup of the drawing area and then created the arc segments using arc and pie generator functions. We plotted the pie and donut segments and customized the chart by adding labels. Finally, we added basic interactivity with tooltips.

Pie and donut charts are useful for showing proportions within a dataset, and now you have the tools to create and customize your own pie and donut charts using D3.

In the next chapter, we will explore how to add animations and transitions in D3.


Ask me anything