How to Create a Pie Chart Using D3.js in 2025?

Creating data visualizations is an essential skill in today’s data-driven world. D3.js has long been a versatile and powerful library for creating rich, interactive visualizations in the web browser. As of 2025, D3.js remains at the forefront of JavaScript libraries for producing stunning data visuals. In this guide, we’ll demonstrate how to create an engaging pie chart using D3.js.
Prerequisites #
Before diving into creating a pie chart, ensure you have a basic understanding of JavaScript, HTML, and CSS. Familiarity with D3.js is a plus.
Step-by-Step Guide to Creating a Pie Chart #
1. Setting Up Your Environment #
To begin with, make sure you have a working HTML file where you can include the D3.js library, either by downloading it locally or linking to a CDN. Here’s a simple HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pie Chart with D3.js</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
/* Add any custom CSS here */
</style>
</head>
<body>
<h1>Pie Chart Example</h1>
<div id="chart"></div>
<script src="script.js"></script>
</body>
</html>
2. Preparing Your Data #
For this example, let’s use a simple dataset:
const data = [
{ label: 'Apples', value: 30 },
{ label: 'Bananas', value: 15 },
{ label: 'Cherries', value: 25 },
{ label: 'Grapes', value: 10 },
{ label: 'Oranges', value: 20 }
];
3. Creating the Pie Chart with D3.js #
In the script.js, add the following code to create the pie chart:
const width = 500;
const height = 500;
const margin = 50;
const radius = Math.min(width, height) / 2 - margin;
const svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', `translate(${width / 2},${height / 2})`);
const color = d3.scaleOrdinal()
.domain(data.map(d => d.label))
.range(d3.schemeCategory10);
const pie = d3.pie()
.value(d => d.value);
const data_ready = pie(data);
svg
.selectAll('path')
.data(data_ready)
.join('path')
.attr('d', d3.arc()
.innerRadius(0)
.outerRadius(radius)
)
.attr('fill', d => color(d.data.label))
.attr('stroke', 'white')
.style('stroke-width', '2px');
4. Adding Interactivity #
To elevate the user experience, you can integrate animations and interactivity into your pie chart. Check D3.js animation techniques for inspiration on creating dynamic effects.
Conclusion #
By following these steps, you should be able to create an engaging and visually appealing pie chart using D3.js. With its vast array of features, D3.js continues to provide ample opportunities for creating interactive and innovative data visualizations.
Explore the D3.js map scaling and other documentation to expand your skills and craft more sophisticated visualizations.
Feel free to customize and experiment with the code to better suit your unique needs and the story you wish to convey through data. Happy coding!