Step 6: Draw peripherals
Our sixth step: drawing peripherals. We draw our axes, learn about the text SVG element, and how to add (and rotate) labels.
Let's finish up our chart by drawing our axes, starting with the x axis.
We want our x axis to be:
a line across the bottom
with spaced "tick" marks that have...
labels for values per tick
a label for the axis overall
To do this, we'll create our axis generator using d3.axisBottom()
, then pass it:
our x scale so it knows what ticks to make (from the domain) and
what size to be (from the range).
xxxxxxxxxx
const xAxisGenerator = d3.axisBottom()
.scale(xScale)
Next, we'll use our xAxisGenerator()
and call it on a new g element. Remember, we need to translate the x axis to move it to the bottom of the chart bounds.
xxxxxxxxxx
const xAxis = bounds.append("g")
.call(xAxisGenerator)
.style("transform", `translateY(${dimensions.boundedHeight}px)`)
When we render our webpage, we should see our scatter plot with an x axis. As a bonus, we can see how using .nice()
on our scale ensures that our axis ends in round values.

Let's expand on our knowledge and create labels for our axes. Drawing text in an SVG is fairly straightforward - we need a <text>
element, which can be positioned with an x
and a y
attribute. We'll want to position it horizontally centered and slightly above the bottom of the chart.
<text>
elements will display their children as text — we can set that with our selection's .html()
method.
This lesson preview is part of the Fullstack D3 Masterclass course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.