A very basic introduction to D3.js

DH Spring Event 29 April 2015

 

Thomas Wielfaert

KU Leuven - Quantitative Lexicology and Variational Linguistics

D3.js

  • First version released in 2011
  • Createdy by Mike Bostock, formerly Stanford, now NYT graphics editor
  • D3 short for Data-Driven Documents
  • .js (Javascript): scripting language that is used in almost all contemporary websites.
  • Combines HTML, SVG and CSS.

@mbostock

HTML (Hypertext Markup Language)

SVG (Scalable Vector Graphics)

CSS (Cascading Style Sheets)

Javascript

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Javascript minimal script</title>
	</head>
	<body>
		<script type="text/javascript">
			alert("Hello world!");
		</script>
	</body>
</html>

Source:

Javascript

JSFiddle to break down the code structure to 3 main components

Minimal D3 script

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>D3 minimal script</title>
		<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
	</head>
	<body>
		<script type="text/javascript">
			d3.select("body").append("p").text("New paragraph!");
		</script>
	</body>
</html>

Result:

Source:

JSFiddle

http://jsfiddle.net (no https!)

Minimal D3 script in JSFiddle

Binding data

Using data (1)

Using data (2)

Drawing a simple bar chart (1)

Drawing a simple bar chart (2)

Drawing a simple bar chart (3)

Drawing a simple bar chart (4)

Drawing circles (1)

Drawing circles (2)

Drawing circles (3)

JSON (JavaScript Object Notation)

Tree structure, similar to XML:

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

JSON

XML

Other data types

Next to JSON, D3 can handle:

  • XML
  • CSV
  • TSV
  • GeoJSON
  • HTML

Force-Directed Graph in JSFiddle

Further reading

  • Text and code examples freely available:

http://alignedleft.com/tutorials/d3

  • D3 Gallery
  • Get help:
    • Stackoverflow
    • Google Groups
Made with Slides.com