US Rainfall Part 7 — plot x coordinate using d3.scaleBand
- Remove Characters from Beginning of JavaScript String
- Divide Large Data Set into Smaller Data Sets
- Handling Radio Buttons in D3.js
- Set Up SVG Viewport with D3.js
- D3.js Data Update Pattern
- 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)
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);
Next Lesson
Generate y-Axis with D3.js scaleLinear