var margin = {top: 20, right: 20, bottom: 20, left: 20}; width = 800 - margin.left - margin.right, height = 500 - margin.top - margin.bottom, formatPercent = d3.format(".1%"); var svg = d3.select("#map").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); tooltip = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); queue() .defer(d3.csv, "smoking-data.csv") .defer(d3.json, "us.json") .await(ready); var legendText = ["", "10%", "", "15%", "", "20%", "", "25%"]; var legendColors = ["#fff7bc", "#fee391", "#fec44f", "#fe9929", "#ec7014", "#cc4c02", "#993404", "#662506"]; function ready(error, data, us) { var counties = topojson.feature(us, us.objects.counties); data.forEach(function(d) { d.year = +d.year; d.fips = +d.fips; d.rate = +d.rate; }); var dataByCountyByYear = d3.nest() .key(function(d) { return d.fips; }) .key(function(d) { return d.year; }) .map(data); counties.features.forEach(function(county) { county.properties.years = dataByCountyByYear[+county.id] }); var color = d3.scale.threshold() .domain([10, 12.5, 15, 17.5, 20, 22.5, 25]) .range(["#fff7bc", "#fee391", "#fec44f", "#fe9929", "#ec7014", "#cc4c02", "#993404", "#662506"]); var projection = d3.geo.albersUsa() .translate([width / 2, height / 2]); var path = d3.geo.path() .projection(projection); var countyShapes = svg.selectAll(".county") .data(counties.features) .enter() .append("path") .attr("class", "county") .attr("d", path); countyShapes .on("mouseover", function(d) { tooltip.transition() .duration(250) .style("opacity", 1); tooltip.html( "
" + d.properties.years[1996][0].county + ", " + d.properties.years[1996][0].state + "
" + "Smoking rate in 1996: | " + formatPercent((d.properties.years[1996][0].rate)/100) + " |
Smoking rate in 2012: | " + formatPercent((d.properties.years[2012][0].rate)/100) + " |
Change: | " + formatPercent((d.properties.years[2012][0].rate-d.properties.years[1996][0].rate)/100) + " |