Generate y-Axis with D3.js scaleLinear

Craig Oda
CodeCakes
Published in
2 min readNov 3, 2018

US Rainfall Part 8 — d3.scaleLinear, d3.extent for min and max

The Code Cakes Project

Previous Lessons

  1. Remove Characters from Beginning of JavaScript String
  2. Divide Large Data Set into Smaller Data Sets
  3. Handling Radio Buttons in D3.js
  4. Set Up SVG Viewport with D3.js
  5. D3.js Data Update Pattern
  6. D3.js Scales for x-Axis
  7. Use D3.js Data for x-coordinate Plotting

Process

Use d3.scaleLinear to generate yScale

Step Overview

  1. Scale
  2. Axis
  3. Group
  4. Update
  5. Call

Scale

const yScale = d3.scaleLinear()
.range([height, 0]);

To create the scale, you will need the domain of data. The domain is the minimum and maximum values of rainfall.

domain

Use d3.extent to get the minimum and maximum values of the data for rainfall. Put this line above the section where you break the data set into smaller data sets.

const rainfallMinMax = d3.extent(data, d => d.rainfall);

The line above grabs the value of rainfall from the full dataset.

csv data file

Set the domain for yScale.

Axis

Create the y-axis. It will not appear on the screen at this stage. Use axisLeft.

const yAxis = d3.axisLeft(yScale);

Group

svg.append('g')

Update

We are not changing the y-axis when the data set changes for this lesson. You do not need to update the y-axis. This will make it easier for the audience to compare the rainfall across the different data sets.

Call

At this stage, the circles do not match yScale. We need to use the data from the CSV file to adjust the height of each circle.

Next Lesson

Set y-coordinate position with D3.js

--

--

Craig Oda
CodeCakes

open source advocate, writer, Flutter developer, father, husband, fly fisherman, surfer