Symbol

Sometimes when visualizing data, we need a simple way to mark data points. That's where symbols come in, which are tiny glyphs we can use as an alternative to circles.

The d3.symbol() generator (from the d3-symbol package) takes a type accessor and a size accessor, and leaves the positioning to us. We will add some symbols to our area chart showing where the function is going when it crosses zero.

As always, we start with a path generator:

const symbols = d3.symbol() 
.type(d => (d[1] > 0 ? d3.symbolTriangle : d3.symbolDiamond))
.size((d, i) => (i % 2 ? 0 : 64));

We've given the d3.symbol() generator a type accessor, telling it to draw a triangle when the y coordinate is positive and a diamond when not positive. This works because our sine data isn't mathematically perfect due to Math.PI not being infinite and due to floating point precision; we get infinitesimal numbers close to zero whose signedness depends on whether the Math.sin argument is slightly less or slightly more than the perfect point for sin=0.

The size accessor tells symbol() how much area each symbol should occupy. Since every other data point is close to zero, we hide the others with an area equal to zero.

Now, we can draw some symbols:

  g2.selectAll('path') 
.data(sine)
.enter()
.append('path')
.attr('d', symbols)
.attr('stroke', 'steelblue')
.attr('stroke-width', 2)
.attr('fill', 'white')
.attr('transform', d => `translate(${x(d[0])},${y(d[1])})`);

Go through the data, append a new path for each entry, and turn it into a symbol moved into position. The result looks as follows:

You can see other available symbols by inspecting d3.symbols or visiting https://github.com/d3/d3-shape/blob/master/README.md#symbols.

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

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