block by mbostock 8033015

Multi-Line Voronoi

Full Screen

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.

Updated Example →

index.html

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

.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: 0.2;
}

#form {
  position: absolute;
  top: 20px;
  right: 30px;
}

</style>
<svg width="960" height="500"></svg>
<label id="form" for="show-voronoi">
  Show Voronoi
  <input type="checkbox" id="show-voronoi" disabled>
</label>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>

var months,
    monthKeys,
    monthParse = d3.timeParse("%Y-%m");

var svg = d3.select("svg"),
    margin = {top: 20, right: 30, bottom: 30, left: 40},
    width = svg.attr("width") - margin.left - margin.right,
    height = svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleTime()
    .range([0, width]);

var y = d3.scaleLinear()
    .range([height, 0]);

var voronoi = d3.voronoi()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); })
    .extent([[-margin.left, -margin.top], [width + margin.right, height + margin.bottom]]);

var line = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });

d3.tsv("unemployment.tsv", type, function(error, data) {
  if (error) throw error;

  x.domain(d3.extent(months));
  y.domain([0, d3.max(data, function(c) { return d3.max(c.values, function(d) { return d.value; }); })]).nice();

  g.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  g.append("g")
      .attr("class", "axis axis--y")
      .call(d3.axisLeft(y).ticks(10, "%"))
    .append("text")
      .attr("x", 4)
      .attr("y", 0.5)
      .attr("dy", "0.32em")
      .style("text-anchor", "start")
      .style("fill", "#000")
      .style("font-weight", "bold")
      .text("Unemployment Rate");

  g.append("g")
      .attr("class", "cities")
    .selectAll("path")
    .data(data)
    .enter().append("path")
      .attr("d", function(d) { d.line = this; return line(d.values); });

  var focus = g.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 = g.append("g")
      .attr("class", "voronoi");

  voronoiGroup.selectAll("path")
    .data(voronoi.polygons(d3.merge(data.map(function(d) { return d.values; }))))
    .enter().append("path")
      .attr("d", function(d) { return d ? "M" + d.join("L") + "Z" : null; })
      .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.data.city.line).classed("city--hover", true);
    d.data.city.line.parentNode.appendChild(d.data.city.line);
    focus.attr("transform", "translate(" + x(d.data.date) + "," + y(d.data.value) + ")");
    focus.select("text").text(d.data.city.name);
  }

  function mouseout(d) {
    d3.select(d.data.city.line).classed("city--hover", false);
    focus.attr("transform", "translate(-100,-100)");
  }
});

function type(d, i, columns) {
  if (!months) monthKeys = columns.slice(1), months = monthKeys.map(monthParse);
  var c = {name: d.name.replace(/ (msa|necta div|met necta|met div)$/i, ""), values: null};
  c.values = monthKeys.map(function(k, i) { return {city: c, date: months[i], value: d[k] / 100}; });
  return c;
}

</script>

Makefile

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 > $@

package.json

{
  "name": "anonymous",
  "version": "0.0.1",
  "private": true,
  "devDependencies": {
    "d3": "3"
  }
}

process-data

#!/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)));