block by kcsluis 3ce3a950e18f39614930

Choropleth Map

Full Screen

index.html

<!DOCTYPE html>

<head>
	<meta charset="utf-8">
	<title></title>
	<style type="text/css">
/*		svg {
			border: 1px solid #f0f;
		}*/
		body {
			font-family: 'arial', sans-serif;
			font-size: 9px;
			width: 960px;
			margin: 30px auto;
		}
		h1 {
			font-size: 36px;
		}
		.g-drought {
			fill: #ccc;
			stroke: #aaa;
			stroke-width: 1px;
		}
	</style>
</head>

<body>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/queue-async/1.0.7/queue.min.js"></script>

<script>

var margin = {top: 20, right: 20, bottom: 20, left: 20};
var width = 960 - margin.left - margin.right,
	height = 540 - margin.top - margin.bottom;
  
var svg = d3.select("body").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 + ")");

var path = d3.geo.path();
// path is a function, called later to draw maps

var color = d3.scale.threshold()
	.domain([-4, -3, -2, 2, 3, 4])
	.range(["#d73027", "#fc8d59", "#fee090", "#ffffbf", "#e0f3f8", "#91bfdb", "#4575b4"]);
	// six breaks, seven colors

queue()
	.defer(d3.json, "//www.karlsluis.com/droughtMap_dbf.json")
	.defer(d3.csv, "//www.karlsluis.com/drought.csv")
	.await(ready);

function ready(error, droughtMap, droughtData) {
	if (error) throw error;

	var droughtByID = {};
	var myYear = 2012;
	var droughtFeatures = topojson.feature(droughtMap, droughtMap.objects.GIS).features;
	// converts topojson into geojson
	// use mapshaper.org for converting shapefiles (shp) into topojson files 

	function drawDroughtMap(theYear) {

		var droughtDataByYear = droughtData.filter( function (d) { return d.year == theYear; });
		droughtDataByYear.forEach( function (d) {
			d.id = +d.id;
			d.val = +d.val;
			d.year = +d.year;
			droughtByID[d.id] = d.val;
		});

		svg.append("g")
			.attr("class", "mapContainer")
		.selectAll("path")
			.data(droughtFeatures)
			.enter()
			.append("path")
			.attr("class", "g-drought")
			.attr("d", path)
			.style("fill", function (d) {
				var thisID = +d.properties.CLIMDIV;
				return color(droughtByID[thisID]);
			});
			// applies data from csv to color json

	};

	drawDroughtMap(myYear);

};

</script>