D3.js Scales for x-Axis

Craig Oda
CodeCakes
Published in
1 min readNov 1, 2018

US Rainfall Part 6 — set up scales and axis

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

In the previous lesson, we plotted circles to correspond to rainfall by state. However, we did not show the state name or the units of rainfall. We’re going to use D3 scales to create both the axis and the position of the circles.

Step Overview

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

Scale

Create xScale above the d3.csv section. Do not set the .domain yet.

const xScale = d3.scaleBand()
.range([0, width])
.padding(0.1);

Axis

const xAxis = d3.axisBottom(xScale);

Group

create xGroup and translate.

const xGroup = svg.append('g')
.attr('transform', `translate(0, ${height})`);

Update

in drawRain, create an array of states for the data set. You will use this data set to update the domain of xScale.

Get States

let states = [];
dataset.forEach(element => {
states.push(element.state);
});

Update Domain

xScale
.domain(states);

Call

xGroup
.call(xAxis);
display x-axis at bottom of chart area

Next Lesson

Use D3.js Data for x-coordinate Plotting

Code Cakes Project Information

--

--

Craig Oda
CodeCakes

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