Before we can start using D3 to create visualizations, we need to get familiar with web standards. The following web standards are heavily used in D3 so we will go over these concepts briefly:
HTML = HyperText Markup Language
HTML is used to structure the content of the web page. The current version is HTML 5. It is stored in a text file with the extension ".html".
A typical bare-bones HTML example looks like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> </body> </html>
Learn HTML from developer.mozilla.org
DOM = Document Object Model
When you write html code for your page, it gets converted to a hierarchical structure on the browser. Every tag in html gets converted to an element in the DOM with a parent-child hierarchy. It makes your html more logically structured. Once the DOM is formed, it makes it easier to manipulate (add/modify/remove) the elements on the page. Remember we had learnt in the first chapter that the first 'D' in D3 stands for Document. D3 gives you the tools to manipulate this DOM via your data.
Learn more about DOM from developer.mozilla.org.
CSS = Cascading Style Sheets
HTML gives a structure to the web page, while CSS styles your web page making it more pleasant to look at. It is a stylesheet language used to describe the presentation of a document written in HTML or XML (including XML dialects like SVG or XHTML). CSS describes how elements should be rendered on a web page.
Learn CSS from developer.mozilla.org.
SVG = Scalable Vector Graphics
SVG is a way to render images on the web page. SVG is not a direct image but is just a way to create images using text. As it's name suggests, it is scalable vector. It scales itself according to the size of the browser, so resizing your browser will not distort the image. All browsers support SVG except IE 8 and below.
Since data visualizations are visual representations, it is convenient to use SVG to render visualizations using D3.
Think of SVG as a canvas on which you can paint different shapes.
So to start off, create an SVG tag:
<svg width="500" height="500"></<svg>
The default measurement for SVG is pixels, so you don't need to specify if your unit is pixel.
Now if you would like to draw a rectangle inside this SVG, draw it using <rect> :
<svg width="500" height="500"> <rect x="0" y="0" width="300" height="200"></rect> </svg>
You can draw the square using <rect> by applying same width and height attribute. Some of the other shapes that can be drawn in SVG include line, circle, ellipse, text and path.
Just like styling html elements, styling SVG elements is simple. Let's color the above rectangle in yellow. All you need to add is an attribute "fill" and specify the color.
<svg width="500" height="500"> <rect x="0" y="0" width="300" height="200" fill="yellow"></rect> </svg>
Learn more about SVG from developer.mozilla.org
Let's start with D3.js by setting up development environment in the next section.