Create Scaled Accessor Functions from D3 Scales

Andy Van Slaars
InstructorAndy Van Slaars
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

When applying scales to data elements in D3, it's common to combine the scale with an accessor function in order to apply the scale to the appropriate key on a data object. In this lesson, we'll create scaled accessors to refactor and tighten up some existing code.

Andy Van Slaars: [0:00] When working with data objects in D3, it's common to have to use an accessor to grab the value off of the data based on its key, and then apply that value to a scale. We see this nesting here with our Y scale wrapped around our Y accessor.

[0:13] Then again, down here for the width, where we use the X accessor, and then wrap the returned value in a call to the X scale. Let's refactor this and create scaled accessors, so that we can clean this code up a little bit and keep our component a little easier to read.

[0:27] I'm going to come up here and right below my definition for bandwidth, I'm just going to define a new constant called scaledX. ScaledX is going to take in a data point and then we'll call scale. The value for X scale is going to be our X accessor applied to our data element.

[0:47] I can duplicate this, and we'll use that as a template to create scaledY, where we apply our Y scale to the result of the Y accessor applied to our data. Now that we have these utilities defined, let's go down into our component code and clean this up just a little bit. We're going to call scaledY on our datum to get our transform. We'll call scaledX on our datum to get the width of our bars.

[1:17] I'll save that and everything should still render exactly the same, but now our component code is a little cleaner, a little easier to read.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today