Last active
March 27, 2017 18:28
-
-
Save hepplerj/f2f4e5f4a9321428b11614674c741177 to your computer and use it in GitHub Desktop.
Threshold scale
This file contains 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(["#fee5d9", "#fcae91", "#fb6a4a", "#de2d26", "#a50f15"]); | |
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("Population density"); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment