This video is available to students only

Adding Labels

We draw a label over each bar, showing the number of points within that bin.

Adding Labels#

Let's add labels to show the count for each of these bars.

We can keep our chart clean by only adding labels to bins with any relevant days — having 0s in empty spaces is unhelpful visual clutter. We can identify which bins have no data by their lack of a bar, no need to call it out with a label.

d3 selections have a .filter() method that acts the same way the native Array method does. .filter() accepts one parameter: a function that accepts one data point and returns a value. Any items in our dataset who return a falsey value will be removed.

By "falsey", we're referring to any value that evaluates to false. Maybe surprisingly, this includes values other than false, such as 0, null, undefined, "", and NaN. Keep in mind that empty arrays [] and object {} evaluate to truthy. If you're curious, read more here.

We can use yAccessor() as shorthand for d => yAccessor(d) != 0 because 0 is falsey.

Since these labels are just text, we'll want to use the SVG <text> element we've been using for our axis labels.

Remember, <text> elements are positioned with x and y attributes. The label will be centered horizontally above the bar — we can find the center of the bar by adding half of the bar's width (the right side minus the left side) to the left side of the bar.


This page is a preview of Fullstack D3 Masterclass

No discussions yet