Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.



    Ben ClinkinbeardBen Clinkinbeard

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



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.