var preterm = function(selector){ var width = 960, height = 500, color = d3.scaleLinear() .range(["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]) .domain([0.08,0.09,0.1,0.11,0.12,0.13]); var svg = d3.select(selector).append("svg") .attr("width", width) .attr("height", height); d3.queue() .defer(d3.tsv, "birthsState.txt") .defer(d3.json, "us.json") .await(ready); function ready(error, preterm, us) { if (error) return console.warn(error); console.log(preterm); console.log(us); console.log(topojson.feature(us, us.objects.states).features); pretermByState = {}; preterm.forEach(function(d) { d["pretermRate"] = +d["pretermRate"]; pretermByState[+d["State Code"]] = d; }); var path = d3.geoPath() .projection(d3.geoAlbersUsa()); var subset = topojson.feature(us, us.objects.states).features.filter(function(d) { return d.id in pretermByState; }); svg.append("g") .attr("class", "states") .selectAll("path") .data(subset) .enter().append("path") .attr("d", path) .style("fill", function(d) { return color(pretermByState[d.id]["pretermRate"]) }) svg.append("path") .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a.id !== b.id; })) .attr("class", "states") .attr("d", path); svg.append("text") .style("font-weight", "bold") .attr("x", width - 195) .attr("y", height - 158) .text("% born <37 weeks"); var legend = svg.selectAll(".legend") .data(color.domain()) .enter().append("g") .attr("transform", function(d,i) { return "translate(" + (width-185) + "," + (height - 150 + 16 * i) + ")"; }) .on("click", function(min,i) { console.log(min,i); }); legend.append("rect") .attr("width", 12) .attr("height", 12) .style("fill", function(d) { return color(d); }); legend.append("text") .attr("x", 16) .attr("y", 7) .attr("alignment-baseline", "middle") .style("font-size", "12px") .text(function(d) { return (d*100).toFixed(0)+"%"; }); } }