Margins
Get introduced to margins and learn how to use them in D3.js.
We'll cover the following
Introduction
In this lesson, we will dive into the last fundamental concept of drawing a chart, margins. Margins are important when we draw charts in D3.js. Without defining margins, our axis will lie on the SVG’s boundaries, and we will have to use translate()
to make it visible. To make drawing charts in D3.js more convenient, we will be using margins in the upcoming lessons.
Although D3.js doesn’t provide an explicit margin component, we will use the translate()
function to draw margins.
Example
Let’s demonstrate margins by going through the following example.
Explanation
See the following explanation with an illustration to understand the above code.
- Line 2-3:
width
andheight
of the chart inside the SVG canvas are calculated by subtracting the margins from the total size of the SVG canvas. - Line 5-10: We have created an SVG canvas of size (400x400).
- Line 25-28: We have created the
chart
of size (320x320) inside the SVG canvas. We have translated thechart
with the help of thetranslate
function as shown in the following illustration.