In this lab we will discuss the basics of using D3.js. You probably noticed in the SVG lab that it is possible to visualize your data by hand typing SVG code. You probably also noticed that this is a painful and repetitive way to make a visualization. It is necessary however to understand how to use SVG to create a visualization. Going forward we'll work (among other things) towards using D3 to accomplish SVG visualization in a less painful way.
In this chapter I will introduce you to how D3 makes it easy to use data to create webpages including SVG visualizations. For now, you can think of D3.js as a tool that takes data and a template of the SVG you want, and writes the SVG for you based on the data.
How to include D3.js
To use D3.js on a webpage you first need include D3.js on the page. There are two options for doing this. I'll explain the pros and cons after explaining the two options. One option is to link to the version of D3.js hosted by the D3.js project. To do this add the following to the webpage's header:
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
The second option is to download a copy of D3.js and host it somewhere else such as on your website or on a content delivery network (CDN). For example, if your website is manning.com, you could put D3.js on your site with the following script tag:
<script src="http://manning.com/js/d3.min.js" charset="utf-8"></script>
The benefit of hosting your own copy is it makes your site independent of the main D3.js site. It also means that the code will not change without your knowledge. In contrast, linking to the project's version of D3.js means that while you will get updates, you're left vulnerable to the main site going down or changing the code in a way that breaks your visualization.
A couple words of warning, unlike many HTML tags that can be used as a single tag, the script tag will not function properly without both an opening and closing tag. For example the following will not work:
<script src="http://d3js.org/d3.min.js" charset="utf-8"/>
Also the charset "utf-8" is required because the D3 source code makes use of special characters such as π.
Things to do
- Include D3.js in the example below
- This site has a copy of D3 located at "d3.min.js". Use this version instead.