Use D3.js Data for x-coordinate Plotting

Craig Oda
CodeCakes
Published in
2 min readNov 2, 2018

US Rainfall Part 7 — plot x coordinate using d3.scaleBand

The Code Cakes Project

  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

Previously, we plotted the x coordinate using the index of the data.

.attr(‘cx’, (d, i) => i * 80)

With this previous technique, the circles are spaced 80 pixels apart. They are not lined up with the x-axis labels and ticks.

To line up the circles with the x-Axis, we need to use xScale.

.attr('cx', d => xScale(d.state))

As d3.scaleBand is generally used with bar charts, the mid-point of the circle is lined up with the left edge of an imaginary bar.

Use bandwith to calculate an offset.

.attr('cx', d => xScale(d.state) + xScale.bandwidth()/2)
center of circle is aligned with ticks on x Axis

Set circle radius to half of the bandwidth.

If you want the circles smaller, you can adjust the padding of the xScale.

const xScale = d3.scaleBand()
.range([0, width])
.padding(0.3);
padding between circles set to 0.3

Next Lesson

Generate y-Axis with D3.js scaleLinear

Code Cakes Project Information

--

--

Craig Oda
CodeCakes

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