D3 is a javascript library that makes it easier to create visualisations in a web browser.
You need to have some understanding of HTML, CSS, and Javascript.
There have been various versions of D3 and some functions are not backwardly compatibale. It originally started in 2011, but Version 4 was released in June 2016, and Verison 5 was released in January 2018.
HTML is made up of elements. Elements usually start and end with a tag. Elements can have attributes. Eg. the element <style> can have the attribute type. Elements can be nested inside each other, and so can have a parent/child heirarchy.
<!DOCTYPE html>
<head>
<style type="text/css">
</style>
<title>D3 Guide</title>
</head>
<body>
<h1>Page One Heading</h1>
<p>Paragraph of text.</p>
</body>CSS consists of selectors and rules. Selectors are the names of the HTML elements or classes that the styles will apply to; Rules are defined within curly brackets { }
p { font-family: sans-serif;
color: lime;
}Bootstrap is a framework that includes a lot of pre-set CSS classes, and that allows you to easily use a grid system.
D3 creates visualisations by using the element (Scalable Vector Graphics) - this draws shapes (eg. circles, rectangles, lines etc..) based on given parameters. In raw HTML this looks like:
<svg width="100" height="100">
<circle cx="50" cy="50" r="20" fill="orange" stroke="gray" stroke-width="2"/>
<rect x="10" y="10" width="50" height="50" fill="lime" stroke-width="4" stroke="pink" />
<line x1="20" y1="40" x2="90" y2="90" stroke="blue" stroke-width="4" />
</svg>The basic D3 code below finds the element and inserts an element inside it: d3.select("body").append("svg");
The D3 library is an object made up of lots of functions. select is a one of these functions (nb. functions that are part of an object are referred to as methods). D3 lets you chain its functions/methods using the . eg d3.method1().method2().method3()
var svg = d3.select("body")
.append("svg")
.attr("width", 1500)
.attr("height", 1500);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + plotheight + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", plotwidth /2 )
.attr("y", margin.bottom )
.text(“Date”); The basic function for reading CSV files is d3.csv().
This function reads and parses the CSV, and converts it into JSON, however this process is asynchronous, so you need the .then(..) is needed to specify what will happen once the file is ready:
d3.csv("dataset.csv")
.then(function(data) {
console.log(data);
// other code to apply to data
});The data in the csv will be read as characters, but you can include the d3.autoType which will try to guess the appropriate data type.
d3.csv("dataset.csv", d3.autoType)
.then(function(data){
// other code to apply to data
});If autoType does not work, you can specify the data types manually instead.