Create a Color Scale with D3's scaleOrdinal

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

In this lesson, we'll clean up some of our placeholder elements. We'll then look at D3's ordinal scale to create a color scale that maps our regions to colors. We'll apply the colors based on region to our data points via the SVG g(group) element to apply the color to both our bars and their corresponding inline labels.

Andy Van Slaars: [0:00] Now that our bar chart is mostly functional, let's clean it up a little bit and make it a little nicer looking. I'm going to start by going into my left axis here. I'm just going to delete this light blue rectangle that we used for placement, and I'll save that.

[0:11] Then I'm going to go back into chart. I'm going to scroll down and I'm going to remove this rectangle with the gray fill that's showing us where our SVG is. Then I'm going to drop down and I'm going to get rid of this light gray rectangle as well. I'll save that.

[0:26] Our chart looks a little cleaner, but it's still lacking visual interest. I'm going to go into my chart component. I'm going to jump up to the top here and I'm going to import another scale from D3. This one is going to be scaleOrdinal.

[0:39] An ordinal scale is going to map a set of discrete values like our regions to another set of discrete values. In this case, we're going to use it to make a color scale. We're going to drop down here, right under our Y scale, and I'm going to create a new constant.

[0:52] I'm going to call it colorScale. This will be a call to scaleOrdinal. Then I'm going to call domain. Our domain for this is going to be our region. It's going to be a map over our data. Then we're going to call the Y accessor on each data element to get those region names. Then we're going to provide it a range. Our range is going to be an array of hex color values.

[1:21] I'll just paste those in. I'm going to scroll down to where I'm rendering. I'm going to take this fill-black off of our rectangles. Then in this group, I'm going to apply fill. My fill value here is going to be a call to colorScale.

[1:38] To that, I'm going to use the Y accessor to pass in the region name for our individual data point. Then I'll save those changes. Now we'll see that we have some nice colors applied both to our bars and the specific data point labels.