var tobacco = function(selector){ var width = 960, height = 500, color = d3.scaleLinear() .range(["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"]) .domain([0.0,0.05,0.10,0.15,0.20,0.25]); 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, tobacco, us) { if (error) return console.warn(error); console.log(tobacco); console.log(us); console.log(topojson.feature(us, us.objects.states).features); tobaccoByState = {}; tobacco.forEach(function(d) { d["tobaccoRate"] = +d["tobaccoRate"]; tobaccoByState[+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 tobaccoByState; }); svg.append("g") .attr("class", "states") .selectAll("path") .data(subset) .enter().append("path") .attr("d", path) .style("fill", function(d) { return color(tobaccoByState[d.id]["tobaccoRate"]) }) d3.selectAll(".states path").each(function(d) { var color = d3.rgb(d3.select(this).style("fill")); if (color.r == 0 && color.g == 0 && color.b == 0) d3.select(this).style("fill", "#eeeeee"); }); 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("% tobacco use"); 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)+"%"; }); } }