Adding Labels
We draw a label over each bar, showing the number of points within that bin.
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 0
s 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 thanfalse
, such as0
,null
,undefined
,""
, andNaN
. 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.
xxxxxxxxxx
const barText = binGroups.filter(yAccessor)
Since these labels are just text, we'll want to use the SVG <text>
element we've been using for our axis labels.
xxxxxxxxxx
const barText = binGroups.filter(yAccessor)
.append("text")
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.