Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
D3 squares example for blog post
function (json) {
var w = 980;
var h = 480;
//get the center of the data
var center = d3.geo.centroid(json);
var svg ="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()
//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()
//draw svg lines of the boundries
.attr("d", path)
.style("fill", function(d){
//applies polygon fills
var ytd =;
var retval = "#edf8fb";
for (i = 0; i < breaks.length; i++) {
if (ytd > breaks[i]){
retval = fills[i];
return retval;
//label the squares with state abbreviations
svg.selectAll(".subunit-label") //this is a style defined elsewhere
.attr("class", function(d) { return "subunit-label " +; })
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment