What is D3.js
– D3 Wiki
After seeing all the demos in the gallery, I bet you will be itching to get your hands dirty with this wonderful library. So lets get started and setup the environment for D3.
If you use npm, install the d3 npm module:
This install the complete D3 library.
Note: D3 v4 is written using ES6 modules. It is composed of a number of microlibraries such as d3-selection, d3-scale, d3-color etc. This modular organization allows us to install and load the modules which are required in our project. On the contrary its predecessor D3 v3 was one big library that we were bound to load in its entirety even if we use only some of the functionalities.
To install a standalone D3 microlibrary:
Ok we have installed our required module successfully. But how do we use it inside our code. If you are familiar with ES6 then you know how to import the module:
If you have installed the complete library:
To load a microlibrary:
In this series we will use the following base template to write all our D3 code:
Throughout this series we will be mostly drawing SVG elements onto our browser. So lets cover some basics on SVG before proceeding to the next section.
- SVG (Scalable Vector Graphics) is an XML-based image format.
- It can be resized and scaled repeatedly and limitlessly without losing any resolution or quality.
- Almost all modern browsers support SVG except IE8 and earlier.
- To draw various shapes in SVG we first need to have a SVG container element. It acts like a canvas where we can draw other geometrical shapes like rectangle, circle, line etc.
Lets look at an example how we can draw the SVG elements in our HTML page:
In this demo you can see the SVG node acting as a container for other SVG shapes like rectangle, circle, line, text etc.
NOTE: In the SVG container the top-left corner is (0,0) . It is the origin and the x axis runs from left to right and y axis runs from top to bottom.
In our next section we will see how to draw these shapes using D3.