Visualizing #D3JS line chart curve styles in #AngularIO

Prior to writing this post I hadn’t realized just how many line charting algorithms D3.js provided. When I started reading about them I thought there would be a fair share of configuration in order to get each one working but to my surprise it was dead simple. With a single line of code a chart can use one of the 18 line curves options that D3.js provides.

In a previous post, Adding a #D3.js line chart to an #Angular.io project, I went over how to create a D3 line chart in Angular. This post will expand on that work to show the various curve options and how to display visual indicators of data points on a chart. If you aren’t familiar with how to get a D3.js chart to work in Angular.io then take a look at the earlier post to get started.

The completed project can be seen running on StackBlitz and the code is available at GitHub. The example shows the following line curves.

  • Default
  • curveBasis
  • curveBasisOpen
  • curveBasisClosed
  • curveBundle
  • curveCardinal
  • curveCardinalOpen
  • curveCardinalClosed
  • curveCatmullrom
  • curveCatmullromOpen
  • curveCatmullromClosed
  • curveLinear
  • curveLinearClosed
  • curveMonotoneX
  • curveMonotoneY
  • curveNatural
  • curveStep
  • curveStepBefore
  • curveStepAfter

As mentioned earlier selecting your curve style is extremely simple. When initializing the line component of the chart, the curve style can be set by calling the curve() function on the line and pass the function for the algorithm to generate the curve. If, for example, you want the line to follow the Cardinal curve algorithm then you would apply that curve by doing line.curve(d3.curveCardinal) before adding the line to the graph svg element. Amazingly enough, that is it. As long as you are going to use a built-in curve you are done.

One thing I noticed was that with some of the curves it can be difficult to tell where the actual data point resides on the chart. To help visualize those points we can add markers to the chart. This next section of code will add a red circle marker with a radius of 5 pixels on each data point.

this.circleMarkers = this.svg
  .selectAll("circle")
  .data(this.data)
  .enter()
  .append("circle")
  .attr("fill", "#ff0000")
  .attr("cx", (d: any) => this.x(d.date))
  .attr("cy", (d: any) => this.y(d.value))
  .attr("r", 5);

The result of a cardinal curve applied to the data and the display of the data points with red circles is shown in the image below . Take a look at all of the examples which are using the same data set but implement different curves to see how the curves differ in style.