Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1083 of the free egghead.io lessons, plus get D3 content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Margins

1:39 D3 lesson by

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

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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

Avatar
Trey

Hi Ben,

I'm not sure if I fully understand how the margins are being set. I understand the object where we are defining all the margins, but I'm having trouble wrapping my mind around why we subtract it from the #chartArea width and height and then add it back in for the SVG width and height. I also don't really understand the "transform" using margin.left + margin.top. Any further explanation would be wonderful.

Thanks

In reply to egghead.io

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?