Skip to content

Instantly share code, notes, and snippets.

@jmduke
Forked from mbostock/.block
Last active August 29, 2015 13:57
Show Gist options
  • Save jmduke/9718647 to your computer and use it in GitHub Desktop.
Save jmduke/9718647 to your computer and use it in GitHub Desktop.

This multi-line chart uses an invisible Voronoi tessellation to handle mouseover; the closest point to the mouse on any line is highlighted. Click the checkbox in the top-right to toggle the visibility of the Voronoi overlay.

Note that because d3.geom.voronoi does not handle coincident points (and this data from the government comes pre-rounded to a tenth of a degree), d3.nest is used to collapse coincident points before constructing the Voronoi.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
width: 960px;
margin: auto;
position: relative;
}
svg {
font: 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.axis--y path {
display: none;
}
.cities {
fill: none;
stroke: #aaa;
stroke-linejoin: round;
stroke-linecap: round;
stroke-width: 1.5px;
}
.city--hover {
stroke: #000;
}
.focus text {
text-anchor: middle;
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}
.voronoi path {
fill: none;
pointer-events: all;
}
.voronoi--show path {
stroke: red;
stroke-opacity: .2;
}
#form {
position: absolute;
top: 20px;
right: 30px;
}
</style>
<label id="form" for="show-voronoi">
Show Voronoi
<input type="checkbox" id="show-voronoi" disabled>
</label>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var months,
monthFormat = d3.time.format("%Y-%m");
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category20();
var voronoi = d3.geom.voronoi()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.value); })
.clipExtent([[-margin.left, -margin.top], [width + margin.right, height + margin.bottom]]);
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.value); });
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 + ")");
d3.tsv("unemployment.tsv", type, function(error, cities) {
x.domain(d3.extent(months));
y.domain([d3.max(cities, function(c) { return d3.max(c.values, function(d) { return d.value; }); }), 0]).nice();
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis()
.scale(x)
.orient("bottom"));
svg.append("g")
.attr("class", "axis axis--y")
.call(d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%"))
.append("text")
.attr("x", 4)
.attr("dy", ".32em")
.style("font-weight", "bold")
.text("Unemployment Rate");
svg.append("g")
.attr("class", "cities")
.selectAll("path")
.data(cities)
.enter().append("path")
.attr("d", function(d) { d.line = this; return line(d.values); });
var focus = svg.append("g")
.attr("transform", "translate(-100,-100)")
.attr("class", "focus");
focus.append("circle")
.attr("r", 3.5);
focus.append("text")
.attr("y", -10);
var voronoiGroup = svg.append("g")
.attr("class", "voronoi");
voronoiGroup.selectAll("path")
.data(voronoi(d3.nest()
.key(function(d) { return x(d.date) + "," + y(d.value); })
.rollup(function(v) { return v[0]; })
.entries(d3.merge(cities.map(function(d) { return d.values; })))
.map(function(d) { return d.values; })))
.enter().append("path")
.attr("d", function(d) { return "M" + d.join("L") + "Z"; })
.datum(function(d) { return d.point; })
.on("mouseover", mouseover)
.on("mouseout", mouseout);
d3.select("#show-voronoi")
.property("disabled", false)
.on("change", function() { voronoiGroup.classed("voronoi--show", this.checked); });
function mouseover(d) {
d3.select(d.city.line).classed("city--hover", true);
d.city.line.parentNode.appendChild(d.city.line);
focus.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")");
focus.select("text").text(d.city.name);
}
function mouseout(d) {
d3.select(d.city.line).classed("city--hover", false);
focus.attr("transform", "translate(-100,-100)");
}
});
function type(d, i) {
if (!i) months = Object.keys(d).map(monthFormat.parse).filter(Number);
var city = {
name: d.name.replace(/ (msa|necta div|met necta|met div)$/i, ""),
values: null
};
city.values = months.map(function(m) {
return {
city: city,
date: m,
value: d[monthFormat(m)] / 100
};
});
return city;
}
</script>
GENERATED_FILES = \
unemployment.tsv
.PHONY: all clean
all: $(GENERATED_FILES)
clean:
rm -rf -- $(GENERATED_FILES)
# http://www.bls.gov/lau/metrossa.htm
build/ssamatab2.txt:
mkdir -p build
curl -o $@ 'http://www.bls.gov/lau/ssamatab2.txt'
unemployment.tsv: process-data build/ssamatab2.txt
./process-data build/ssamatab2.txt > $@
{
"name": "anonymous",
"version": "0.0.1",
"private": true,
"devDependencies": {
"d3": "3"
}
}
#!/usr/bin/env node
var fs = require("fs"),
d3 = require("d3");
// Parse lines.
var lines = fs.readFileSync(process.argv[2], "utf8").split(/[\r\n]+/);
// Parse fixed-width columns.
var data = lines.filter(function(d, i) {
return i >= 3 && i <= lines.length - 4;
}).map(function(line) {
var fields = line.split(/\s{2,}/), i = -1;
return {
"LAUS Code": fields[++i],
"State FIPS Code": fields[++i],
"Area FIPS Code": fields[++i],
"Area": fields[++i],
"Year": fields[++i],
"Month": fields[++i],
"Civilian Labor Force": +fields[++i].replace(/,/g, ""),
"Employment": +fields[++i].replace(/,/g, ""),
"Unemployment": +fields[++i].replace(/,/g, ""),
"Unemployment Rate": +fields[++i]
};
});
// Extract the available dates.
var dates = d3.set(data.map(function(d) { return d["Year"] + "-" + d["Month"]; })).values().sort();
// Nest unemployment rate by area and date.
var rateByNameAndDate = d3.nest()
.key(function(d) { return d["Area"]; })
.key(function(d) { return d["Year"] + "-" + d["Month"]; })
.rollup(function(v) { return v[0]["Unemployment Rate"]; }) // leaf nest is unique
.map(data, d3.map);
// Recast data into a wide table.
var rows = rateByNameAndDate.entries().sort(function(a, b) { return d3.ascending(a.key, b.key); }).map(function(area) {
return [area.key].concat(dates.map(function(d) {
return area.value.get(d);
}));
});
process.stdout.write(d3.tsv.formatRows([["name"].concat(dates)].concat(rows)));
date charlotte-bobcats philadelphia-76ers miami-heat washington-wizards milwaukee-bucks new-york-knicks chicago-bulls detroit-pistons cleveland-cavaliers boston-celtics brooklyn-nets indiana-pacers orlando-magic toronto-raptors atlanta-hawks
20131029 3 3 1 3 3 3 14 3 3 3 3 1 14 3 3
20131105 4 2 3 14 11 13 11 4 4 15 4 1 4 4 4
20131112 7 4 2 14 8 8 4 14 8 4 8 1 8 8 3
20131119 5 6 2 11 15 11 3 6 9 11 11 1 6 9 4
20131126 4 9 2 6 15 14 4 6 12 10 12 1 10 6 3
20131203 7 9 2 3 15 14 5 5 12 8 13 1 11 9 4
20131210 4 12 2 5 15 14 7 5 9 7 11 1 13 10 3
20131217 6 14 2 6 15 13 9 4 10 4 10 1 12 8 3
20131224 4 13 2 4 15 11 9 6 10 8 11 1 13 7 3
20131231 6 13 2 4 15 13 9 7 10 7 10 1 10 5 3
20140107 7 12 2 5 15 11 6 8 12 10 9 1 14 4 3
20140114 8 12 2 5 15 10 5 7 11 12 8 1 14 3 3
20140121 8 12 2 4 15 10 4 8 10 12 7 1 14 4 3
20140128 8 12 2 5 15 9 5 9 11 12 7 1 14 3 3
20140204 8 13 2 5 15 10 6 9 11 12 7 1 14 3 4
20140211 8 14 2 6 15 10 4 9 11 12 7 1 13 3 5
20140218 8 14 2 6 15 11 4 9 10 12 6 1 13 3 5
20140225 7 14 2 5 15 11 4 9 10 12 6 1 13 3 8
20140304 7 14 2 5 15 11 4 9 10 12 6 1 13 3 7
20140311 7 14 2 5 15 10 4 9 11 12 6 1 13 3 8
20140318 7 14 2 5 15 9 4 10 10 12 5 1 13 3 8
20140325 7 14 2 6 15 9 4 10 10 12 5 1 13 3 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment