-
Notifications
You must be signed in to change notification settings - Fork 2
Home
Ryan Gates edited this page Nov 4, 2015
·
17 revisions
This tutorial is taken largely from Let’s Make a Bar Chart.
- Fork or download this repo
- 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?
- 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");-
d3.select(".chart")grabs our chart div from the html -
.selectAll("div")grabs all of the div elements it can find -
.data(inputData, function(d) { return d["Jan 2015"];})joins our data with div tags-
.data()can accept a key function which allows us to handle complex objects
-
-
index.htmlshould render a blank page but there will be a div for each entry in the data

- 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 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.

- 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.

- Add the below javascript function to show the data values on mouse over
.attr("title", function(d) { return d[jan2015] + " riders for January 2015."})- Here we're using the
.attr()function to set the title to create a tooltip effect
- Add the below fragment to use the
d3.format()function to add comma separators
d3.format(",")(d["Jan 2015"])- The final code will look like below.
d3.select(".chart")
.selectAll("div")
.data(inputData, function(d) { return d["Jan 2015"];})
.enter().append("div")
.attr("title", function(d) { return d3.format(",")(d["Jan 2015"]) + " riders for January 2015."})
.style("width", function(d) {
return x(d["Jan 2015"]) + "px";
})
.text(function(d){ return d.Name; });- And the output will look like this screenshot
