5.x implementation of a choropleth map, using Promises.
Forked from mbostock's block: Choropleth
forked from adamjanes's block: Choropleth V5
xxxxxxxxxx
<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.v5.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>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var unemployment = d3.map();
var path = d3.geoPath();
var x = d3.scaleLinear()
.domain([1, 10])
.rangeRound([600, 650]);
var color = d3.scaleLinear()
// .domain(d3.range(-50, 0, 5))
.domain([-50,
-45,-40,-35,-30,-25,-20,-15,-10,-5,
0
])
.range(["#890024",
"#A94138",
"#C86E4F",
"#E19E6F",
"#F2CD97",
"#FFFFC2",
"#CCDCB5",
"#98BAA8",
"#6A9799",
"#447586",
"#195473",
"#195473"
])
.clamp(true);
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(0,40)");
// g.selectAll("rect")
// .data(color.range().map(function(d) {
// d = color.invertExtent(d);
// if (d[0] == null) d[0] = x.domain()[0];
// if (d[1] == null) d[1] = x.domain()[1];
// return d;
// }))
// .enter().append("rect")
// .attr("height", 8)
// .attr("x", function(d) { return x(d[0]); })
// .attr("width", function(d) { return x(d[1]) - x(d[0]); })
// .attr("fill", function(d) { return color(d[0]); });
// g.append("text")
// .attr("class", "caption")
// .attr("x", x.range()[0])
// .attr("y", -6)
// .attr("fill", "#000")
// .attr("text-anchor", "start")
// .attr("font-weight", "bold")
// .text("Unemployment rate");
// g.call(d3.axisBottom(x)
// .tickSize(13)
// .tickFormat(function(x, i) { return i ? x : x + "%"; })
// .tickValues(color.domain()))
// .select(".domain")
// .remove();
var promises = [
d3.json("https://d3js.org/us-10m.v1.json"),
d3.tsv("unemployment.tsv", function(d) { unemployment.set(d.id, +d.rate); })
]
Promise.all(promises).then(ready)
function ready([us]) {
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("fill", function(d) { return color(d.rate = unemployment.get(d.id)); })
.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>
https://d3js.org/d3.v5.min.js
https://d3js.org/d3-scale-chromatic.v1.min.js
https://d3js.org/topojson.v2.min.js