Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<style>
.counties :hover {
fill: red;
}
.county-borders {
fill: none;
stroke: #fff;
stroke-width: 0.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src ="https://d3js.org/topojson.v2.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script>
var width = 960, height = 500;
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
var threshold = d3.scaleThreshold()
.domain([1, 10, 20, 200, 800, 2000, 5000, 10000])
.range(d3.schemeOrRd[9]);
d3.queue()
.defer(d3.json, 'https://umbcvis.github.io/classes/class-12/tracts.json')
.defer(d3.json, 'https://umbcvis.github.io/classes/class-12/population.json')
.await(ready);
var projection = d3.geoConicConformal()
.parallels([38 + 18 / 60, 39 + 27 / 60])
.rotate([77, -37 -40 / 60]);
var path = d3.geoPath()
.projection(projection);
function ready(error, json, population) {
if (error) throw error;
// Convert topojson to GeoJSON
geojson = topojson.feature(json, json.objects.counties);
counties = geojson.features;
// Set the projection's scale and translate based on the GeoJSON
projection.fitSize([960, 500], geojson);
// Extract an array of features (one tract for each feature)
counties.forEach(function(county) {
var countyfips = counties.properties.COUNTYFP;
var countyfp = counties.properties.COUNTYFP;
pop = population.filter(function(d) { return (d[2] === countyfips)
&& (d[3] === COUNTYFP);
});
pop = +pop[0][0];
var aland = counties.properties.ALAND / 2589975.2356; //area in square miles
tract.properties.density = pop / aland;
});
svg.selectAll('path.tract')
.data(counties)
.enter()
.append('path')
.attr('class', 'counties')
.attr('d', path)
.style('fill', function (d) {return threshold(d.properties.density); })
.style('stroke', '#000')
}
addLegend();
function addLegend() {
var formatNumber = d3.format("d");
var x = d3.scalePow().exponent('.15')
.domain([1, 80000])
.range([0, 300]);
var xAxis = d3.axisBottom(x)
.tickSize(13)
.tickValues(threshold.domain())
.tickFormat(formatNumber)
var g = svg.append("g")
.attr('transform', 'translate(100, 200)')
.call(xAxis);
g.select(".domain")
.remove();
g.selectAll("rect")
.data(threshold.range().map(function(color) {
var d = threshold.invertExtent(color);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().insert("rect", ".tick")
.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 threshold(d[0]); });
g.append("text")
.attr("fill", "#000")
.attr("font-weight", "bold")
.attr("text-anchor", "start")
.attr("y", -6)
.text("Population per square mile");
}
</script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-scale-chromatic.v1.min.js