1. Starting with D3: Selections
The first function we will use to start with D3 is for selection. To select an item in D3, we use d3.select(""). It is functionally very similar to using document.getElementById("") or document.querySelector("").
In D3, the special thing about the .select() function is that we can select any type of element present in the DOM. For example, we can choose by:
- ID using
#id - Class using
.class - HTML elements like
d3.select("div")
The .select function will choose only one element at a time from the DOM. If the selector matches more elements, it will select the first one. Let's look at an example:
If we run the following code:
Now, if you want to select all the li elements, D3 provides a function called d3.selectAll().
2. Appending New Elements
To append a new element in the DOM we use d3.append(). For example, if we want to add a new <li>Four</li> into our existing <ul>, we would chain the commands like this:
The "Method Chaining" Pattern
Why does the code above work? Because almost every D3 method (like
.select(),.append(), or.attr()) returns a selection object. This allows you to chain multiple commands together gracefully, instead of assigning intermediary variables for every step like you might in vanilla JavaScript.
3. Creating the SVG Container
Using this very basic information, let us start with D3.js. We will create the SVG container. This will be the canvas in which we will create our charts and maps. Let's learn to append it and set basic attributes.
This code selects the container, appends an <svg> element to it, and then sets its height and width to 500 pixels. This forms the foundational viewport for our subsequent visualizations.
4. Drawing Your First Shape
Now that we have a 500x500 SVG canvas, let's actually draw something on it using the coordinate system we just learned. Let's draw a circle.
Because we set cx and cy to exactly half of our 500px canvas, this code will place a perfectly centered indigo circle right in the middle of our SVG.