This video is available to students only

Draw data

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

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.

Unlock This Course

Get unlimited access to Fullstack D3 Masterclass with a single-time purchase.

Thumbnail for the \newline course Fullstack D3 Masterclass