Search⌘ K
AI Features

Adding the SVG Element

Understand how to add an SVG element to your web page using D3, define its size and margins, and use a group element to position your graph. This lesson shows how to prepare the drawing area properly for creating simple interactive graphs with D3.

As the title states, the next piece of script forms and adds the SVG element to the web page that D3 will then use to draw on.

The code to add SVG

JavaScript (JSX)
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");

What exactly does this mean?

Well D3 needs to be able to have a space defined for it to draw things. When we define the space it’s going to use, we can also give the space we’re going to use an identifying name and attributes.

In the example we’re using ...