Margins

Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 5 years ago

This lesson will show you how to add margins to your D3 charts to give them the elbow room they deserve.

Ben Clinkinbeard: There's a well established way in D3 to add margins to charts. You can do things like add axes without affecting the rest of your charting code. The way you do that is with a margin object like you see here.

Once you have that margin object defined, you are going to want to update your width and height properties and subtract the horizontal properties from your width and the vertical properties from your height, so you're working with an inner size to the chart.

Once you do that, you need to add those margin properties back into the code that creates the SBG tag. Our SBG tag is filling up that whole outer size of 400 by 300.

The last step is to add a G element which is a graphics container in SBG. Then offset that graphic element by our left and top margins.

It is worth noting that since we're appending this G element, our SBG variable up here is going to be referring to that graphic element and not the SBG tag itself. Since the G element is what we want to work with, that's OK.

Since we started with margins of zero for everything, nothing looks different. It looks the same as it did before. You can see now, if we go up here and modify those properties, our chart will update and redraw itself and give us plenty of room to create our axes here.

egghead
egghead
~ just now

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