Last updated
How Pie Charts Work
A pie chart represents data as slices of a circle, where each slice's angle is proportional to its value relative to the total. A slice representing 25% of the total spans 90° (25% of 360°). Pie charts are best for showing part-to-whole relationships with a small number of categories (2–6). With more categories, a bar chart is usually more readable.
Slice Angle Calculation
function drawPieChart(canvas, data) {
// data = [{ label: 'A', value: 30 }, ...]
const ctx = canvas.getContext('2d');
const cx = canvas.width / 2;
const cy = canvas.height / 2;
const radius = Math.min(cx, cy) - 20;
const total = data.reduce((s, d) => s + d.value, 0);
const colors = ['#3498DB','#2ECC71','#E74C3C','#F1C40F','#9B59B6','#1ABC9C'];
let startAngle = -Math.PI / 2; // start at top
data.forEach((slice, i) => {
const sliceAngle = (slice.value / total) * 2 * Math.PI;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, radius, startAngle, startAngle + sliceAngle);
ctx.closePath();
ctx.fillStyle = colors[i % colors.length];
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.stroke();
startAngle += sliceAngle;
});
}
Pie Chart Best Practices
- Limit to 5–6 slices maximum. Group smaller values into an "Other" category.
- Start the first slice at 12 o'clock (top) for natural reading.
- Avoid 3D pie charts — they distort the perceived size of slices.
- Use direct labels on slices rather than a legend when possible.
- Consider a donut chart (hollow center) for a more modern look — same data, better readability.
When Not to Use a Pie Chart
Avoid pie charts when comparing values that are close in size (humans are poor at judging angles), when you have more than 6 categories, or when showing change over time. Bar charts and line charts are almost always more accurate for comparison tasks.