|
<!DOCTYPE html> |
|
<meta charset="utf-8"> |
|
<style> |
|
|
|
.counties { |
|
fill: none; |
|
} |
|
|
|
.states { |
|
fill: none; |
|
stroke: #fff; |
|
stroke-linejoin: round; |
|
} |
|
|
|
</style> |
|
<svg width="960" height="600"></svg> |
|
<script src="https://d3js.org/d3.v4.min.js"></script> |
|
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> |
|
<script src="https://d3js.org/topojson.v2.min.js"></script> |
|
<script> |
|
|
|
// goal: change the color scale |
|
var color = d3.scaleLinear() |
|
.domain([2, 4, 6, 50]) |
|
.range(["gold", "white", "white","black"]); |
|
|
|
// array gets populated with unemployment rates |
|
// could use mungeData to extract median, etc |
|
var rateArray = []; |
|
|
|
|
|
var fillFunction = function(d) { |
|
console.log(d.rate = unemployment.get(d.id)) |
|
// d.id is the id of the county |
|
return color(d.rate = unemployment.get(d.id)); |
|
} |
|
|
|
/////////////////////////////// |
|
|
|
var svg = d3.select("svg"), |
|
width = +svg.attr("width"), |
|
height = +svg.attr("height"); |
|
|
|
var unemployment = d3.map(); |
|
|
|
var path = d3.geoPath(); |
|
|
|
var g = svg.append("g") |
|
.attr("class", "key") |
|
.attr("transform","translate(0,40)"); |
|
|
|
|
|
// get data for us county shapes and unemployment data |
|
d3.queue() |
|
.defer(d3.json, "https://d3js.org/us-10m.v1.json") |
|
.defer(d3.tsv, "unemployment.tsv", function(d) { |
|
// parse tsv |
|
rateArray.push(+d.rate) |
|
unemployment.set(d.id, +d.rate); |
|
}) |
|
.await(ready); |
|
|
|
function ready(error, us) { |
|
if (error) throw error; |
|
|
|
// unemployment data is a dictionary of county id to unemployment rate |
|
|
|
// draw us counties |
|
svg.append("g") |
|
.attr("class", "counties") |
|
.selectAll("path") |
|
.data(topojson.feature(us, us.objects.counties).features) |
|
.enter().append("path") |
|
// fill determines color |
|
.attr("fill", fillFunction) |
|
.attr("d", path) |
|
.append("title") |
|
.text(function(d) { return d.rate + "%"; }); |
|
|
|
svg.append("path") |
|
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; })) |
|
.attr("class", "states") |
|
.attr("d", path); |
|
|
|
} |
|
|
|
</script> |