Skip to content
Ryan Gates edited this page Nov 4, 2015 · 17 revisions

This tutorial is taken largely from Let’s Make a Bar Chart.

Getting Started

  1. Fork or download this repo
  2. Add appropriate references to your index.html
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
	<link href="index.css" rel="stylesheet">
</head>
<body>
	<div class="chart"></div>
	<script type="text/javascript" src="index.js"></script>
</body>
</html>
  • Who can tell me why the script below referencing our index.js is at the bottom of the body?

Incorporating Data

Creating the Skeleton

  1. Add in the following code to create some skeleton elements
d3.select(".chart")
	.selectAll("div")
	.data(inputData, function(d) { return d["Jan 2015"];})
	.enter().append("div");

Adding the Title

  1. Add the below line to the index.js file
.text(function(d){ return d.Name; });
  • The .text() function adds text to the div tags that are created for each entry in the list.
  • The end result will look like below
d3.select(".chart")
	.selectAll("div")
	.enter().append("div")
	.text(function(d){ return d.Name; });

Add some color

  1. Add the following to your index.css file
.chart div {
	font: 10px sans-serif;
	background-color: steelblue;
	text-align: right;
	padding: 3px;
	margin: 1px;
	color: white;
}
  • One significant benefit of d3 is that it's output is html and can be styled as you would an html element

It should now look something like the below.

Sorting our data

  1. Add the below line of code to sort the data
inputData = inputData.sort(function(x,y) { return y["Jan 2015"] - x["Jan 2015"]; });
  • Here we are using the javascript .sort() function to order our data.
  • The end result looks like below.

Clone this wiki locally