Interactive Maps
Housekeeping
Office hours this Sunday 4pm to 6pm.
Please add more to the things we don’t get wiki if you’re having problems with anything or there’s anything you want us to cover.
Here’s a cool free book.
Critique
Diego will be discussing this animated video of income inequality.
Your Big Project
Lab
This week we’ll be building a D3 version of last week’s map.
Go to your maps-intro project. We’ll be using the same project repo this week.
Create interactive-map.html
Add D3 to the page.
Create the margin conventions
var margin = {top: 20, right: 20, bottom: 20, left: 20}; width = 750 - margin.left - margin.right, height = 700 - 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 + ")");
Now, let’s load our dataset – it should be called
merged-multirace.txt
– andconsole.log(data)
to see it in the chrome javascript console.Next we need some geodata. Thankfully I’ve prepared some for you – download this file to your project: california counties topojson
Let’s load it up… unfortunately we need use of queue
queue() .defer(d3.tsv, "merged-multirace.txt") .defer(d3.json, "ca-counties.json") .await(ready); function ready(error, data, ca) { //data is loaded and ready! }
I’ve prepared it in a topojson format. In order to properly use it, we need to add support for topojson and then convert our data back into GeoJSON so D3 can draw it.
var counties = topojson.feature(ca, ca.objects.counties);
Now that we’re loading up both files, let’s inspect the ca counties data.
First we need to add a projection. Let’s start with mercator.
var projection = d3.geo.mercator();
Next, we need to create something that will generate our paths for us based on this projection.
var path = d3.geo.path() .projection(projection);
One more step and we’ll have a map. Let’s do a data join which will create one path for each county.
svg.selectAll(".county") .data(counties.features) .enter().append("path") .attr("class", "county") .attr("d", path);
That doesn’t look that great, let’s revisit the projection. First, something better for a state, like albers.
var projection = d3.geo.albers();
Let’s add these one at a time and see what they do.
.translate([width / 2, height / 2])
.parallels([34, 40.5])
.rotate([120, 0])
.scale(3000);
We can add a few styles
.county { fill: grey; stroke: black; }
What we really want though is to color it from the data. In order to do that we need to merge our datasets together.
Convert our data to numbers.
Filter to just 2020.
Merge on fips code
Now, log our data join…
Create a color scale
Fill by pcthispanic