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%.
-
-
Save git-ashish/3f7f86edf4ef46efb2c4585d1fa53ade to your computer and use it in GitHub Desktop.
Threshold Key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| license: gpl-3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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> | |
| var formatPercent = d3.format(".0%"), | |
| formatNumber = d3.format(".0f"); | |
| var threshold = d3.scaleThreshold() | |
| .domain([0.11, 0.22, 0.33, 0.50]) | |
| .range(["#6e7c5a", "#a0b28f", "#d8b8b3", "#b45554", "#760000"]); | |
| var x = d3.scaleLinear() | |
| .domain([0, 1]) | |
| .range([0, 240]); | |
| var xAxis = d3.axisBottom(x) | |
| .tickSize(13) | |
| .tickValues(threshold.domain()) | |
| .tickFormat(function(d) { return d === 0.5 ? formatPercent(d) : formatNumber(100 * d); }); | |
| 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("Percentage of stops that involved force"); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment