This video is available to students only

Draw peripherals

We draw a line depicting the mean of our distribution, as well as our axes.

Draw peripherals#

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.

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?

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.

 

This page is a preview of Fullstack D3 Masterclass

Please select a discussion on the left.