We finally get to draw our bars! We draw them in groups, so we can position them as well as labels.
Here comes the fun part! Our plan is to create one bar for each bin, with a label on top of each bar.
We'll need one bar for each item in our
bins array — this is a sign that we'll want to use the data bind concept we learned in Module 2.
Let's first create a
<g> element to contain our bins. This will help keep our code organized and isolate our bars in the DOM.
Because we have more than one element, we'll bind each data point to a
<g> SVG element. This will let us group each bin's bar and label.
To start, we'll select all existing
<g> elements within our
binsGroup (there aren't any yet, but we're creating a selection object that points to the right place). Then we'll use
.data() to bind our
bins to the selection.
Next, we'll create our
<g> elements, using
.join() to target all of our bins.
The above code will create one new
<g> element for each bin. We're going to place our bars within this group.
Next up we'll draw our bars, but first we should calculate any constants that we'll need. Like a warrior going into battle, we want to prepare our weapons before things heat up.
In this case, the only constant that we can set ahead of time is the padding between bars. Giving them some space helps distinguish individual bars, but we don't want them too far apart - that will make them hard to compare and take away from the overall shape of the distribution.
Chart design tip: putting a space between bars helps distinguish individual bars
Now we are armed warriors and are ready to charge into battle! Each bar is a rectangle, so we'll append a
<rect> to each of our