Last active
May 25, 2016 14:55
-
-
Save geobabbler/5c0b450ebb6e79f37e27 to your computer and use it in GitHub Desktop.
D3 squares example for blog post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
d3.json( | |
"data/statistics.geojson", | |
function (json) { | |
//dimensions | |
var w = 980; | |
var h = 480; | |
//get the center of the data | |
var center = d3.geo.centroid(json); | |
var svg = d3.select("body").append("svg") | |
.attr("width", w) | |
.attr("height", h); | |
//create the projection used to display the data | |
//equirectangular for plate carrée in this case | |
//use scale and center to orient D3 to our arbitrary geometries | |
var projection = d3.geo.equirectangular() | |
.scale(2500) | |
.precision(.77) | |
.center(center); | |
//breaks were chosen arbitrarily for this example | |
var breaks = [20, 15, 10, 5]; | |
//defines polygon fills for each break | |
var fills = ['#006d2c','#2ca25f','#66c2a4','#b2e2e2']; | |
//defines label colors, applying white when polygon fill gets too dark | |
var textcolors = ['#ffffff','#ffffff','#000000','#000000']; | |
//create geo.path object, set the projection to merator bring it to the svg-viewport | |
var path = d3.geo.path() | |
.projection(projection); | |
//draw svg lines of the boundries | |
svg.append("g") | |
.selectAll("path") | |
.data(json.features) | |
.enter() | |
.append("path") | |
.attr("d", path) | |
.style("fill", function(d){ | |
//applies polygon fills | |
var ytd = d.properties.ytd; | |
var retval = "#edf8fb"; | |
for (i = 0; i < breaks.length; i++) { | |
if (ytd > breaks[i]){ | |
retval = fills[i]; | |
break; | |
} | |
} | |
return retval; | |
}); | |
//label the squares with state abbreviations | |
svg.selectAll(".subunit-label") //this is a style defined elsewhere | |
.data(json.features) | |
.enter().append("text") | |
.attr("class", function(d) { return "subunit-label " + d.id; }) | |
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; }) | |
.attr("dy", ".35em") | |
.text(function(d) { return d.properties.abbr; }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment