Data functions of D3

D3 comes with a bunch of helper functions for manipulating arrays. They mostly have to do with handling data; things like calculating averages, ordering, bisecting arrays, and more. In D3 v4, they're found in the d3-array package.

Of all the D3 pieces of documentation that you'll read, the one for d3-array is definitely one of the most useful. We'll cover a few of d3-array's more useful functions, but there is far more to it than we'll be able to reasonably go over in just one chapter. I even sometimes find it useful to have the README for d3-array open in a tab while I develop, because it also acts as a very good quick reference for each method's function signature; you can visit it at 
https://github.com/d3/d3-array.

Briefly, some of the more useful functions in d3-array are as follows; most of them can take an accessor function, which is used when working with arrays of objects to specify which property should be used for the calculation:

  • d3.min and d3.max return the smallest and largest values in the array respectively. d3.extent returns an array with both values.
  • d3.sum, d3.mean, and d3.median are useful for doing these types of calculations on an array. It's important to use medians and means responsibly; displaying a mean on a dataset with a lot of extreme values at either end risks distorting the middle values. We'll discuss this a little bit more later on in Chapter 10, Designing Good Data Visualizations.
  • d3.ascending and d3.descending are pre-built comparator functions, so you don't have to remember which number you need to subtract from each number when sorting. It also ensures that numbers are sorted in natural order, and not alphabetical order (as is the default behavior of Array.prototype.sort if you sort numbers typed as strings, an issue we'll get into when we talk about static typing later on in the book).
  • We've already used d3.range a few times already. Supply it two integer numbers and it will return an array with those values and every intermediary value between them; it includes the first number, not the last number. It can be provided a third value that specifies how big the step between intermediary values should be, defaulting to 1. Note that this can be used on nonintegers, but with reduced accuracy; refer to the documentation for full details.

d3-array also contains d3.histogram, which we'll use later on, in Chapter 7, The Other Layouts, to make histogram charts. I'm only mentioning it here because it's a bit more complex to explain; note that it's in the same package as all of the above.

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

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