Built with blockbuilder.org
xxxxxxxxxx
<svg width="1100" height="1500"></svg>
<style>
.hidden {
display: none;
}
div.tooltip {
color: #fff;
background-color: DarkGoldenRod;
padding: .5em;
font-family: Arial;
font-size: 12px;
font-weight: bolder;
border-radius: 2px;
opacity: 0.7;
position: absolute;
}
</style>
<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>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var path = d3.geoPath();
var color = d3.scaleThreshold()
.domain([1, 10, 50, 200, 500, 1000, 2000, 4000])
.range(d3.schemeYlOrRd[9]);
var x = d3.scaleSqrt()
.domain([0, 4500])
.rangeRound([440, 1050]);
var tooltip = d3.select('body').append('div')
.attr('class', 'hidden tooltip');
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(-50,825)");
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("Population per square mile");
g.call(d3.axisBottom(x)
.tickSize(13)
.tickValues(color.domain()))
.select(".domain")
.remove();
d3.json("nv-topo.json", function(error, topology) {
if (error) throw error;
svg.append("g")
.selectAll("path")
.data(topojson.feature(topology, topology.objects.tracts).features)
.enter().append("path")
.attr("fill", function(d) { return color(d.properties.density); })
.attr("d", path)
.attr("y",400)
.on('mousemove', function(d) {
var mouse = d3.mouse(svg.node()).map(function(d) {
return parseInt(d);
});
tooltip.classed('hidden', false)
.attr('style', 'left:' + (mouse[0] + 15) +
'px; top:' + (mouse[1] - 25) + 'px')
.html(d.properties.density + " residents per square mile");
})
.on('mouseout', function() {
tooltip.classed('hidden', true);
});
;
svg.append("path")
.datum(topojson.feature(topology, topology.objects.counties))
.attr("fill", "none")
.attr("stroke", "DarkGoldenRod")
.attr("stroke-opacity", 0.6)
.attr("d", path)
});
</script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-scale-chromatic.v1.min.js
https://d3js.org/topojson.v2.min.js