Search⌘ K

Setting Up the Margins and the Graph Area

Explore how to set up margins and graph area in D3 by breaking down the JavaScript code. Understand margin definitions and dynamic sizing to create adaptable graphs without complex calculations.

Let’s understand the JavaScript (JS) of the code first by breaking it into the various components that comprise the graph.

The code for the margins

The part of the code responsible for defining the area where the graph and associated bits and pieces are placed is this part:

JavaScript (JSX)
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

Explanation of the code

Line 1: Defines the four margins which surround the block where the graph (as an object) is positioned.

So, there will be a border of:

  • 20 pixels at the top
  • 20 pixels at the right
...