Zimt

Animated Pie & Donut Charts in D3.js

· 5 min read · Pastry and Pies

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to build animated pie and donut charts using D3.js (version 7). You'll learn to create the SVG arcs, add smooth transitions when data changes, and style both chart types. By the end, you'll have a reusable function that renders either a pie or donut with animated entry and updates.

What You'll Need

  • A basic understanding of HTML, CSS, and JavaScript
  • D3.js library (v6 or v7) – include via CDN or download locally
  • A code editor and a modern web browser
  • Your data as an array of objects with numeric values (e.g., [{label: "A", value: 30}, ...])

Step-by-Step

  1. Set up the HTML structure. Create an HTML file with a container div (e.g., <div id="chart"></div>) and include D3 via a script tag. For local development, you can use a simple HTTP server.
  2. Define your data. Use an array of objects. For example: const data = [{name: "Apples", value: 10}, {name: "Bananas", value: 20}, {name: "Cherries", value: 30}];
  3. Set up chart dimensions and radius. Choose a width and height (e.g., 400x400). For a donut, define an inner radius (e.g., 80) and an outer radius (e.g., 150). For a pie, inner radius is 0.
  4. Create the SVG container. Append an svg element to your div, set its width and height, and add a g element centered in the middle: const svg = d3.select("#chart").append("svg").attr("width", w).attr("height", h); const g = svg.append("g").attr("transform", `translate(${w/2}, ${h/2})`);
  5. Create the pie generator. Use d3.pie() to compute the start and end angles from your data: const pie = d3.pie().value(d => d.value).sort(null); The sort(null) keeps your original order.
  6. Create the arc generator. Use d3.arc() to generate the SVG path data: const arc = d3.arc().innerRadius(innerR).outerRadius(outerR); For a pie, set innerR to 0.
  7. Bind data and draw initial arcs. Select all path elements, bind the pie data, and append paths. Set the d attribute using the arc generator. Add a fill color – you can use a categorical scale like d3.scaleOrdinal(d3.schemeCategory10).
  8. Add animation on initial render. To animate the arcs appearing, start with d as a zero-length arc (e.g., d => arc({startAngle: d.startAngle, endAngle: d.startAngle})) and then transition to the full arc. Use .transition().duration(750).attr("d", arc).
  9. Add labels (optional). For each slice, compute the centroid using arc.centroid(d) and place a text element there. Animate opacity with the same transition.
  10. Handle updates. When data changes, re-bind the data and use the general update pattern. For arcs, update the d attribute with a transition. For entering arcs, start from zero angle. For exiting arcs, transition to zero angle and then remove.
  11. Add interactivity (optional). Add mouseover effects like enlarging a slice by increasing the outer radius slightly. You can create a separate arc for hover and transition to it.

Common Mistakes

  • Forgetting to sort data – if you want a specific order, use .sort(null); otherwise D3 sorts by value.
  • Using the wrong arc for hover – if you modify the arc generator in place, all slices will change. Create a separate arc for hover effects.
  • Not handling enter/exit selections – when data changes, new slices may appear and old ones may vanish; you must handle both transitions.
  • Centering issues – if the chart appears off-center, check that the g transform uses the correct width/height divided by 2.
  • Ignoring the sort parameter – by default, D3 sorts slices by value; use .sort(null) to keep your data order.

Tips

  • Use d3.transition() to create a reusable transition with a consistent duration and easing.
  • For donut charts, consider adding a center label with total or average; position it with the same g transform.
  • Use arc.centroid(d) to place labels – it gives the midpoint of the arc.
  • When animating updates, use arc as the target and a zero-angle arc as the start/end for enter/exit.
  • Test with a small dataset first to debug quickly.
  • Use d3.interpolate for smooth color transitions if you want to animate colors when data changes.

Troubleshooting

  • Chart doesn't appear: Check the console for errors. Ensure the SVG is appended to the correct div and that your data is defined. Verify that the g transform is correct.
  • Arcs are not shaped correctly: Make sure you're passing the pie data (which includes startAngle and endAngle) to the arc generator, not the raw data.
  • Animation doesn't run: Ensure you call .transition() on the selection and that the transition duration is set. Also, check that you're not overriding the d attribute after the transition.
  • Labels are upside down or overlapping: Adjust the label position using arc.centroid and consider adding a small offset. For small slices, you may need to hide labels or use a leader line.
  • Update causes weird jumps: Use key functions when binding data (e.g., .data(pieData, d => d.data.name)) to match entering and exiting elements correctly.

Frequently Asked Questions

How do I create a pie chart instead of a donut?

Set the inner radius to 0 in the arc generator: d3.arc().innerRadius(0).outerRadius(outerR).

Can I animate the chart when data changes?

Yes, use the general update pattern: bind new data, transition existing arcs to new angles, add new arcs from zero, and remove exiting arcs by transitioning to zero.

How do I add a legend?

You can create a separate SVG group and add colored rectangles or circles with labels. Position it to the right or below the chart.

How do I make the chart responsive?

Use a viewBox on the SVG and set width/height to 100%. Or use JavaScript to resize on window events and recompute the radius.

Can I use D3 v4 or v5?

Yes, the code is largely compatible. The main difference is that in v6+, d3.pie and d3.arc are in the default namespace, but they work similarly.

How do I change the color scheme?

Replace d3.schemeCategory10 with any array of colors or a custom scale like d3.scaleOrdinal(["#ff0000", "#00ff00", ...]).