Clarify Data in D3 with Additional Labels and Rounded Domain Values

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

Looking at our bars against each other with the x-axis as a guide gives us some relative information, but doesn't deliver the most precise values. In this lesson, we'll add additional labels to show the exact values of each data point in the context of the individual bars.

Instructor: [0:00] The bars on our chart represent our data values and we can see using the x-axis roughly what our values are, but we don't have exact amounts. Let's add additional labels to this so that we can clarify our data.

[0:12] Here in chart, we're mapping over our data and we're rendering a rectangle for each one of these. We're going to wrap this in a group so that we can render a rectangle and a text element for each data point. I'm going to drop down here and I'm going to create a new group element.

[0:26] In this group element, I'm going to give this a key and I'm going to calculate that key based on the Y accessor and data. Then I'm going to move my transform from my rectangle up to my group.

[0:40] Then I'm going to put the closing group after my rectangle, and I'm going to save that. At this point, everything should render just the same. Now that we have our group, I'm going to go inside the group, right after my rectangle, and I'm going to add a new text element.

[0:53] I'm going to give this a font weight. I'm going to set that to boulder. I'm going to give this a dominant baseline of hanging. Then I want to give this transform. My transform is going to take a translate. I got to translate the X and I'm going to use the scaled X, scaled accessor that we created earlier. I'm going to pass a datum.

[1:17] Then I'm going to add four to that. This is just going to push our label over to the right of the bar, and give it a little bit of space. Then inside my text element, we're going to use the X accessor with datum to show the exact data value for each bar. We can save this.

[1:37] We'll see that each bar has its exact value sitting right next to it to the top right. Notice that the additional label for the north region is hanging off to the side here. Let's open up app. In app, we could adjust this by changing the right margin to give this more space.

[1:52] Everything will get recalculated and our label will fit. We'll notice a new problem. The north value is actually 221 and our X scale is only showing up to 220. Let's reset our right margin to 15 pixels. Let's go back into chart and see if we can fix this using our X scale.

[2:11] We'll scroll up to the X scale. After domain, we're going to drop down. We're going to add a call to the nice method and we'll save that. We'll see that our x-axis is now showing up to 240, and our bars have been bumped in. Everything fits within our bounded dimensions.