Share this video with your friends

Send Tweet
Published 8 years ago
Updated 3 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.