This video is available to students only

Step 2: Create chart dimensions

The second step: creating chart dimensions. This time, we learn how to create a square chart that fits within any browser window.

Create chart dimensions#

Next up, we need to define the dimensions of our chart. Typically, scatterplots are square, with the x axis as wide as the y axis is tall. This makes it easier to look at the overall shape of the data points once they're plotted by not stretching or squashing one of the scales.

To make a square chart, we want the height to be the same as the width. We could use the same width we used in Module 1 (window.innerWidth * 0.9), but then the chart might extend down the page, out of view on horizontal screens.

Ideally, the chart will be as large as possible while still fitting on our screen.

To fix this problem, we want to use either the height or the width of the window, whichever one is smaller. And because we want to leave a little bit of whitespace around the chart, we'll multiply the value by 0.9 (so 90% of the total width or height).

d3-array can help us out here with the d3.min method. d3.min takes two arguments:

  1. an array of data points

  2. an accessor function to grab the value from each data point

Though in this case we won't need to specify the second parameter because it defaults to an identity function and returns the value.

There is a native browser method (Math.min) that will also find the lowest number — why wouldn't we use that? Math.min is great, but there are a few benefits to d3.min:

  • Math.min will count any nulls in the array as 0, whereas d3.min will ignore them

  • Math.min will return NaN if there is a value in the array that is undefined or can't be converted into a number, whereas d3.min will ignore it

  • d3.min will prevent the need to create another array of values if we need to use an accessor function

  • Math.min will return Infinity if the dataset is empty, whereas d3.min will return undefined

  • Math.min uses numeric order, whereas d3.min uses natural order, which allows it to handle strings. Make sure to convert your values to numbers beforehand

You can see how d3.min would be preferable when creating charts, especially when using dynamic data.

 

This page is a preview of Fullstack D3 Masterclass

No discussions yet