Course contentsShow
← Web Development
Lesson 2607 of 2,98247. Data VisualizationFree lesson

Creating Pie and Donut Charts

Generate circular charts using SVG arcs and path commands with trigonometric calculations.

Creating Pie and Donut Charts

You'll learn: How to generate circular charts using SVG arcs and path commands combined with trigonometric calculations to visualize proportional data.

The Core Idea

Pie and donut charts display data as slices of a circle, where each slice's angle corresponds to its proportion of the whole. Unlike rectangles (bars) or connected points (lines), circular charts require drawing arc paths using SVG's path element. The math involves converting your data percentages into angles, then using trigonometry to calculate the start and end coordinates of each arc.

Think of it like cutting a pizza: you need to know where each slice starts and ends around the circle's edge. SVG paths don't have a built-in "arc from angle A to angle B" command—you must calculate the exact X,Y coordinates using sine and cosine functions.

How It Works

  1. Calculate angles: Convert each data value into a percentage of the total, then multiply by 360° (or 2π radians)
  2. Track cumulative angles: Each slice starts where the previous one ended
  3. Convert to coordinates: Use Math.cos() and Math.sin() with your radius to find points on the circle's edge
  4. Draw the arc: Use SVG's M (move), A (arc), and L (line) path commands to create each slice
  5. For donuts: Draw a smaller inner circle and use two arcs per slice

The A command syntax is: A rx ry rotation large-arc-flag sweep-flag x y. For pie charts, you'll typically use large-arc-flag (0 or 1) to indicate whether the arc spans more than 180°.

Pie vs Donut

Pie charts fill the entire circle; donut charts leave the center hollow by drawing both an outer and inner arc, creating a ring shape. Same math, just two radii instead of one.

Key Takeaway: Pie and donut charts require converting data percentages into angular coordinates using trigonometry, then drawing SVG arcs with calculated start/end positions around a circle's circumference.