Introduction to D3.js
Day 1


April 1, 2014
P V

Recap

HTML Base
bit.ly/1pFk8l9
<!DOCTYPE html><html><head>  <title>D3.js Demo</title>  <style> /* CSS goes here */ </style>  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script></head><body>
<script> /* JS goes here */ </script>
</body></html>

Recap

Creating an SVG Canvas


var w = 800,
  h = 500;
  
var svg = d3.select('body')
  .append('svg')
  .attr('width', w)
  .attr('height', h);
  

Map Projections

D3.js provides sub-library for geo stuff.
Want projection: data -> canvas


var projection = d3.geo.albersUsa()
  .scale(900)
  .translate([w/2, h/2]);
 
var path = d3.geo.path()
  .projection(projection);


Map Data


Comes in TopoJSON / GeoJSON format

Import sub-library to utilize:


<script src="http://d3js.org/topojson.v1.min.js"></script>


Map Data

Where's the map data?

Need to get it elsewhere...

http://www.tnoda.com/blog/2013-12-07

For your convenience, get U.S. data here:

bit.ly/1pKhSJk

Map Data

Save & Import



<script src="us.js"></script>


Create Map


Add the states...


map.append('g')
  .attr('class', 'states')
  .selectAll('path')
  .data(topojson.feature(us, us.objects.states).features)
  .enter()
  .append('path')
  .attr('d', path);


Create Map

...and the borders!


map.append('path')
  .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
  .attr('class', 'state-borders')
  .attr('d', path);


Create Map


Style things

  .state-borders {
  stroke: grey;
  stroke-width: 2px;
  fill: none;
}

.states {
  fill: lightblue;
}


Add Points to Map

Some places to display:
bit.ly/1mJ9xZa

var cityData = [
  {
    name : "New York",
    lat : 40.77,
    lon : -73.98
  },
  {
    name : "San Francisco",
    lat : 37.75,
   lon : -122.68
  },
  {
    name : "Boston",
    lat : 42.37,
    lon : -71.03
  }
];

???


To be added.

Intro to D3.js: Day 2

By liviro

Intro to D3.js: Day 2

  • 1,213