Building shapes with d3


Some shapes can be quite complex—like rings, slices, paths, polygons, and curves. Manually creating the d attribute for these shapes would be a nightmare!

Fortunately, D3 provides a module called d3-shape specifically for handling all these shapes. Let's explore how it can simplify our work.

Members only
4 minutes read

Building the line you need

In the previous lesson we introduced the path element, and showed that a line chart is basically rendered this way:

<svg height="300" width="400">
  <path
    d="M0 105 L100 200 L200 200 L300 20 L350 120"
    fill="none"
    stroke="#69b3a2"
  />
</svg>

We also learned that d3 includes a module called d3-shape, which offers a variety of helper functions for building shapes. These functions take your data and automatically generate the d attribute for a path!

Now, let's explore how to use the d3.line() function to create the path for a line chart:


const data = [
  { x: 0, y: 40 },
  { x: 50, y: 70 },
  { x: 100, y: 150 },
  ...
];

Everything begins with a data object, which is almost always an array.

Each item in the array represents a data point and is usually an object with properties.

For a line chart like the one above, you'll need at least two properties: one for the x-axis position and one for the y-axis position.

Oh no! 😱

This lesson isn’t available just yet.

Take a look at the status badges next to each lesson in the sidebar to see when it’s coming out.

Thanks for your patience! 🙏