block by hugolpz 4f4958fd6a9306e82082

Choropleth with makefile

Full Screen

[By: mbostock. Forked for later adaptation]. This variation of the unemployment choropleth uses topojson –projection to create projected TopoJSON with the d3.geo.albersUsa projection.

This example also uses the -e argument to join the county geometries with a TSV file of unemployment rates, simplifying the implementation and eliminating the need to load multiple data files.

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.counties {
  fill: none;
}

.state-borders {
  fill: none;
  stroke: #fff;
  stroke-linejoin: round;
  stroke-linecap: round;
}

.q0-9 { fill:rgb(247,251,255); }
.q1-9 { fill:rgb(222,235,247); }
.q2-9 { fill:rgb(198,219,239); }
.q3-9 { fill:rgb(158,202,225); }
.q4-9 { fill:rgb(107,174,214); }
.q5-9 { fill:rgb(66,146,198); }
.q6-9 { fill:rgb(33,113,181); }
.q7-9 { fill:rgb(8,81,156); }
.q8-9 { fill:rgb(8,48,107); }

</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>

var width = 960,
    height = 500;

var quantize = d3.scale.quantize()
    .domain([0, .15])
    .range(d3.range(9).map(function(i) { return "q" + i + "-9"; }));

var path = d3.geo.path()
    .projection(null);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("us.json", function(error, us) {
  if (error) return console.error(error);

  svg.append("g")
      .attr("class", "counties")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
    .enter().append("path")
      .attr("class", function(d) { return quantize(d.properties.rate); })
      .attr("d", path);

  svg.append("path")
      .datum(topojson.mesh(us, us.objects.counties, function(a, b) { return a.id / 1000 ^ b.id / 1000; }))
      .attr("class", "state-borders")
      .attr("d", path);
});

</script>

Makefile

GENERATED_FILES = \
	us.json

.PHONY: all clean

all: $(GENERATED_FILES)

clean:
	rm -rf -- $(GENERATED_FILES) build

build/%.tar.gz:
	mkdir -p $(dir $@)
	curl -o $@ 'http://dds.cr.usgs.gov/pub/data/nationalatlas/$(notdir $@)'

build/counties-unfiltered.shp: build/countyp010_nt00795.tar.gz
	@rm -rf -- $(basename $@)
	mkdir -p $(basename $@)
	tar -xzm -C $(basename $@) -f $<
	for file in `find $(basename $@) -type f`; do chmod 644 $$file; mv $$file $(basename $@).$${file##*.}; done
	rm -rf -- $(basename $@)

build/counties.shp: build/counties-unfiltered.shp
	@rm -f -- $@
	ogr2ogr -f 'ESRI Shapefile' -where "FIPS NOT LIKE '%000'" $@ $<

us.json: build/counties.shp
	node_modules/.bin/topojson \
		-o $@ \
		--projection 'd3.geo.albersUsa()' \
		-q 1e5 \
		-s 1 \
		-e unemployment.tsv \
		-p rate=+rate \
		--id-property=id,+FIPS \
		-- build/counties.shp

package.json

{
  "name": "anonymous",
  "version": "0.0.1",
  "private": true,
  "devDependencies": {
    "topojson": "1"
  }
}