Shape generators
🎯 Introduction
Bars use rect, but lines and pie slices need SVG path elements. Writing their path strings by hand quickly becomes impractical. D3 shape generators convert data into paths so you can build line, area, and pie charts.
🧱 Why use generators?
Here is what an SVG line looks like underneath. The d attribute of a path describes its shape:
<svg width="400" height="300">
<path d="M0,180 L100,60 L200,120 L300,240" fill="none" stroke="#5470c6" />
</svg>
M0,180 means “move to (0,180)”; L100,60 means “draw a line to (100,60)”. Four points are manageable, but a string containing 500 points is difficult to maintain.
Here is that hand-written path rendered as a line connecting four points:
A shape generator is a function that generates the d string: pass in data and receive a path string.
🧱 d3.line: line charts
d3.line() creates a line generator. Its .x() and .y() accessors specify how to obtain each point's coordinates:
const line = d3
.line()
.x(d => xScale(d.day)) // Each point's x coordinate
.y(d => yScale(d.value)); // Each point's y coordinate
line(data); // Return a string such as "M0,180 L100,60 L200,120..."
Bind the entire data array to one path:
svg.append('path')
.datum(data) // One line is a single graphic: bind the entire array
.attr('d', line) // Convert the bound data into a path
.attr('fill', 'none')
.attr('stroke', '#5470c6')
.attr('stroke-width', 2);
- The entire line uses one path. Bind the array with
datum(data), rather than distributing it withdata(data), which is used when creating separate paths for individual items. - Set
fill: 'none'. Otherwise, the default black fill turns the line into a solid shape. :::
scalePoint is a good choice. Its usage resembles scaleBand, but it returns point positions directly without a bar width:const xScale = d3.scalePoint().domain(['Mon', 'Tue', 'Wed', 'Thu', 'Fri']).range([0, width]);
xScale('Wed'); // Exactly at the midpoint
🧱 curve: smooth curves
By default, a line consists of straight segments. Add.curve() to smooth it:const line = d3
.line()
.x(d => xScale(d.day))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX); // Smooth interpolation through every data point
d3.curveMonotoneX is a common choice: the curve passes through the actual data points without introducing overshoot between them.The rendered smooth curve passes through every red data point:The smooth curve passes through every red data point without overshooting.
🧱 d3.area: area charts
Think of an area chart as a line chart with a filled region beneath it. It adds a second boundary:y0 is the lower boundary and y1 the upper boundary:const area = d3
.area()
.x(d => xScale(d.day))
.y0(height) // Lower boundary: fixed at the bottom
.y1(d => yScale(d.value)); // Upper boundary: follows the data
svg.append('path').datum(data).attr('d', area).attr('fill', 'rgba(84, 112, 198, 0.3)');
.curve() for the line and area. Otherwise, a smooth line over a straight-edged area leaves visible gaps between the fill boundary and the line.🧱 d3.arc + d3.pie: pie charts
Two generators work together:pie calculates angles, and arc draws slices.First, pie converts values into start and end angles for each slice:const data = [
{ name: 'Phones', value: 45 },
{ name: 'Computers', value: 30 },
{ name: 'Tablets', value: 25 },
];
const pie = d3.pie().value(d => d.value);
pie(data); // Return a new array containing angles
pie(data) looks roughly like this. Angles are in radians; a full circle is approximately 6.28:[
{ data: { name: 'Phones', value: 45 }, startAngle: 0, endAngle: 2.83 },
{ data: { name: 'Computers', value: 30 }, startAngle: 2.83, endAngle: 4.71 },
{ data: { name: 'Tablets', value: 25 }, startAngle: 4.71, endAngle: 6.28 },
];
pie calculates.Next, arc converts those angles into slice paths:const arc = d3.arc().innerRadius(0).outerRadius(150); // Inner radius: 0; outer radius: 150
const colors = ['#5470c6', '#91cc75', '#fac858'];
svg.selectAll('path')
.data(pie(data)) // Bind the angle data produced by pie
.join('path')
.attr('d', arc) // Generate a slice from each datum's angles
.attr('fill', (d, i) => colors[i]);
innerRadius from 0 to 80, leaving a hole in the center. That single parameter distinguishes it from a pie chart.❓ Questions and answers
Q1: Why is my line chart a solid black shape?You forgotfill: 'none'. By default, a path fills its enclosed region, producing a black polygon.Q2: How do I position pie-chart labels?Use arc.centroid(d) to obtain the center coordinates for each slice, then place a text element there.Q3: Which curve options are available?Common options are curveLinear (default straight segments), curveMonotoneX (smooth), and curveStep (stepped). Start with curveMonotoneX.Q4: Can an area's lower boundary be somewhere other than the bottom?Yes. y0 also accepts a function. In a stacked area chart, for example, one layer's lower boundary follows the top of the layer below. Start with a fixed baseline while learning.🧪 Exercise
Build a combined line and area chart for a week of sales data:- Use
scalePointfor the x scale andscaleLinearfor the y scale. - Draw a translucent area with
d3.area(). - Overlay a smooth line using
d3.line()withcurveMonotoneX.
const data = [
{ day: 'Mon', value: 120 },
{ day: 'Tue', value: 200 },
{ day: 'Wed', value: 150 },
{ day: 'Thu', value: 80 },
{ day: 'Fri', value: 70 },
];
onMounted(() => {
// Write your code here
});
🎉 You now know the three main shape generators! Next, we will animate charts with transitions.
