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 takes two arguments:
an array of data points
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.minis great, but there are a few benefits to
Math.minwill count any
nulls in the array as
d3.minwill ignore them
NaNif there is a value in the array that is
undefinedor can't be converted into a number, whereas
d3.minwill ignore it
d3.minwill prevent the need to create another array of values if we need to use an accessor function
Infinityif the dataset is empty, whereas
Math.minuses numeric order, whereas
d3.minuses natural order, which allows it to handle strings. Make sure to convert your values to numbers beforehand
You can see how
d3.minwould be preferable when creating charts, especially when using dynamic data.