Draw peripherals
We draw a line depicting the mean of our distribution, as well as our axes.
When looking at the shape of a distribution, it can be helpful to know where the mean is.
The mean is just the average — the center of a set of numbers. To calculate the mean, you would divide the sum by the number of values. For example, the mean of [1, 2, 3, 4, 5]
would be (1 + 2 + 3 + 4 + 5) / 5 = 3
.
Instead of calculating the mean by hand, we can use d3.mean()
to grab that value. Like many d3 methods we've used, we pass the dataset as the first parameter and an optional accessor function as the second.
xxxxxxxxxx
const mean = d3.mean(dataset, metricAccessor)
Great! Let's see how comfortable we are with drawing an unfamiliar SVG element: <line>
. A <line>
element will draw a line between two points: [x1, y1]
and [x2, y2]
. Using this knowledge, let's add a line to our bounds that is:
at the mean humidity level,
starting 15px above our chart, and
ending at our x axis.
How close can you get before looking at the following code?
xxxxxxxxxx
const meanLine = bounds.append("line")
.attr("x1", xScale(mean))
.attr("x2", xScale(mean))
.attr("y1", -15)
.attr("y2", dimensions.boundedHeight)
Let's add some styles to the line so we can see it (by default, <line>
s have no stroke color) and to distinguish it from an axis. SVG element strokes can be split into dashes with the stroke-dasharray
attribute. The lines alternate between the stroke color and transparent, starting with transparent. We define the line lengths with a space-separated list of values (which will be repeated until the line is drawn).
Let's make our lines dashed with a 2px long maroon dash and a 4px long gap.
xxxxxxxxxx
const meanLine = bounds.append("line")
.attr("x1", xScale(mean))
.attr("x2", xScale(mean))
.attr("y1", -15)
.attr("y2", dimensions.boundedHeight)
.attr("stroke", "maroon")
.attr("stroke-dasharray", "2px 4px")
Give yourself a pat on the back for drawing your first <line>
element!

Let's label our line to clarify to readers what it represents. We'll want to add a <text>
element in the same position as our line, but 5 pixels higher to give a little gap.
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.