Area

An area is the colored part between two lines, think of an area chart, which shows you the space beneath a curve.

Similar to how we define a line, we create a path generator and tell it how to use our data. For a simple horizontal area, we have to define one x accessor and two y accessors, y0 and y1, because our area has a top and a bottom. Often the bottom y accessor will just be zero because the y-axis frequently starts at zero. This isn't always the case, however, and D3 gives you the power to handle any particular case you might run into.

We'll compare different generators side by side. Start by adding a new group element, which we'll render inside the same SVG element:

const g2 = chart.container.append('g') 
.attr('transform',
`translate(${(chart.width / 2) + (chart.margin.left + chart.margin.right)},
${chart.margin.top})`);

Now, we define an area generator and draw an area:

  const area = d3.area() 
.x(d => x(d[0]))
.y0(chart.height / 2)
.y1(d => y(d[1]))
.curve(d3.curveBasis);

g2.append('path')
.datum(sine)
.attr('d', area)
.attr('fill', 'steelblue')
.attr('fill-opacity', 0.4);

We took the d3.area() path generator and told it to get the coordinates through the x and y scales we defined earlier. The basis interpolator will use a B-spline to create a smooth curve from our data.

D3 v4 change: Yep, you guessed it--d3.svg.area is now just simply d3.area. It's part of the d3-shapes microlib.

To draw the bottom edge, we defined y0 as the bottom of our graph and produced a colored sine approximation:

One often uses an area in conjunction with a line. We can either give the path a border using its stroke property, or we could use our line generator to render another line atop the top edge of our area. Let's try the latter:

g2.append('path') 
.datum(sine)
.attr('d', line.curve(d3.curveBasis))
.attr('stroke', 'steelblue')
.attr('stroke-width', 2)
.attr('fill', 'none');

Reusing the same line generator as before, we merely change the interpolator for the area:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset