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.


This page is a preview of Fullstack D3 Masterclass

Start a new discussion. All notification go to the author.