I'm stumped by what I'd hoped would be a minor tweak to Mike Bostock's unemployment choropleth ( https://bl.ocks.org/mbostock/4060606 ): adding the county names and state abbreviations to the .tsv file.
I created a new unemployment2.tsv by merging Bostock's original with a list of county ID codes, names and states from the Census bureau. A sample:
id rate state county
01001 5.1 AL Autauga County
01003 4.9 AL Baldwin County
...
56043 4.5 WY Washakie County
56045 4.9 WY Weston County
In the javascript, I modified the d3.queue() block as follows, in an attempt to access the state and county columns:
d3.queue()
.defer(d3.json, "https://d3js.org/us-10m.v1.json")
.defer(d3.tsv, "unemployment2.tsv", function(d) {
unemployment.set(d.id, +d.rate, d.county, d.state);
county = d.county;
state = d.state;
})
.await(ready);
I then modified the tooltip line of the svg.append block as follows:
.text(function(d) { return d.id + " - " + county + ", " + state + " - " + d.rate + "%"; });
The resulting map does access the new columns in the .tsv file, but the tooltip displays the county and state only from the last line (Weston County, WY) no matter which county you mouse over. (Oddly, the id and rate fields do reflect the correct county in the tooltip.)
I’m seeing the same behavior on my server as on Plunker ( https://plnkr.co/edit/vrm4FuBVEQc7lCSnbytl?p=preview ).
Appreciate any insights as to what I'm doing wrong/how to fix.
To do this you need to understand how d3.map()
works.
A d3 map creates key entry pairs, map.get("key")
returns the value associated with that key. To create an entry in a map we use map.set("key",value)
. In your code block you use:
unemployment.set(d.id, +d.rate, d.county, d.state);
Where unemployment
is your map and d
is a row in the tsv. Using this we set the value associated with each key (d.id
) to be d.rate
, which is only one part of the data we want in the original example. The extra parameters, d.county
and d.state
here are ignored.
Instead, we could use:
unemployment.set(d.id, d);
This will set the key to be d.id
still, as above, but now the value is the entire row of the tsv that we want:
unemployment.get("06071"); // { id: "06071", rate: "6.2", state: "CA", county: "San Bernardino County" }
In the original example the value in the map was a string, but now it is an object representing a row in the tsv, so we need to address a few lines in the original example:
.attr("fill", function(d) { return color(unemployment.get(d.id)); })
Becomes:
.attr("fill", function(d) { return color(unemployment.get(d.id).rate); })
As we need to access the rate property of the mapped value.
And for the tooltip, we can use:
.text(function(d) { var datum = unemployment.get(d.id); return "ID: " + datum.id + " - " + datum.county + ", " + datum.state + " - " + "Rate: " + datum.rate + "%"; });
Which gives us this.