var obesity = function(selector){ var width = 960, height = 500, color = d3.scaleLinear() .range(["#fff5eb","#fdd0a2","#fd8d3c","#d94801","#7f2704"]) .domain([0.20,0.25,0.30,0.35]); 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, obesity, us) { if (error) return console.warn(error); console.log(obesity); console.log(us); console.log(topojson.feature(us, us.objects.states).features); obesityByState = {}; obesity.forEach(function(d) { d["obesityRate"] = +d["obesityRate"]; obesityByState[+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 obesityByState; }); svg.append("g") .attr("class", "states") .selectAll("path") .data(subset) .enter().append("path") .attr("d", path) .style("fill", function(d) { return color(obesityByState[d.id]["obesityRate"]) }) 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 - 170) .attr("y", height - 158) .text("% obesity"); var legend = svg.selectAll(".legend") .data(color.domain()) .enter().append("g") .attr("transform", function(d,i) { return "translate(" + (width-160) + "," + (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)+"%"; }); } }