Skip to content

Instantly share code, notes, and snippets.

@fdaudens
Created August 14, 2017 02:59
Show Gist options
  • Save fdaudens/dd2768f5c0e5b8aa4d676d2d9c989144 to your computer and use it in GitHub Desktop.
Save fdaudens/dd2768f5c0e5b8aa4d676d2d9c989144 to your computer and use it in GitHub Desktop.
Threshold Key
license: gpl-3.0

This example demonstrates how to construct a key from a threshold scale, in the style of Ford Fessenden’s map of police stops involving force. A linear scale is used to set the x-position of each colored rectangle in the key. There is one rectangle per color in the threshold scale’s range, and one tick per value in the threshold scale’s domain. The linear scale’s domain sets the implied extent of the key, here spanning 0 to 100%.

forked from mbostock's block: Threshold Key

<!DOCTYPE html>
<svg width="960" height="500"><g transform="translate(360,250)"></g></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/colorbrewer.v1.min.js"></script>
<script>
var formatPercent = d3.format(".0%"),
formatNumber = d3.format("0");
var threshold = d3.scaleThreshold()
.domain([1, 10, 50, 200, 500, 1000, 2000, 4000])
.range(colorbrewer.OrRd[9]);
var x = d3.scaleSqrt()
.domain([0, 4500])
.rangeRound([1, 300]);
var xAxis = d3.axisBottom(x)
.tickSize(10)
.tickValues(threshold.domain());
var g = d3.select("g").call(xAxis);
g.select(".domain")
.remove();
g.selectAll("rect")
.data(threshold.range().map(function(color) {
var d = threshold.invertExtent(color);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().insert("rect", ".tick")
.attr("height", 8)
.attr("x", function(d) { return x(d[0]); })
.attr("width", function(d) { return x(d[1]) - x(d[0]); })
.attr("fill", function(d) { return threshold(d[0]); });
g.append("text")
.attr("fill", "#000")
.attr("font-weight", "bold")
.attr("text-anchor", "start")
.attr("y", -6)
.text("Densité");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment