Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active March 10, 2017 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pbogden/86a9f77dd337ee7b1f8d to your computer and use it in GitHub Desktop.
Save pbogden/86a9f77dd337ee7b1f8d to your computer and use it in GitHub Desktop.
legend

reusable legend

d3.legend = function() {
// Defaults
var t = [0, 0],
cb = null,
colors = d3.scaleOrdinal()
.domain(["A", "B", "C", "D"])
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);
var box = 38,
padding = 2,
dx = box + padding;
function legend(selection) {
selection.each(function() {
var legend = d3.select(this).selectAll(".legend")
.data( colors.domain().slice().reverse() )
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(" + t[0] + "," + (t[1] + i * dx) + ")"; });
legend.append("rect")
.attr("x", 0 )
.attr("width", box)
.attr("height", box)
.style("fill", colors);
legend.append("text")
.attr("x", - 2 * padding )
.attr("y", box / 2)
.attr("dy", ".35em")
.style("text-anchor", "end")
.style("font-size", "0.8em")
.text(function(d) { return d; });
if (typeof cb == "function") cb();
})
}
legend.translate = function(_) {
if (!arguments.length) return t;
t = _;
return legend;
};
legend.colors = function(_) {
if (!arguments.length) return colors;
colors = _;
return legend;
};
legend.cb = function(_) {
if (!arguments.length) return cb;
cb = _;
return legend;
};
return legend;
}
<!DOCTYPE html>
<meta charset="utf-8">
<title>legend</title>
<style>
body {
font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="d3.legend.js"></script>
<script>
var margin = {top: 50, right: 50, bottom: 50, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.bottom - margin.top;
var colors = d3.scaleOrdinal()
.domain( ["A", "B", "C", "D"] )
.range(["#fe9929", "#ec7014", "#cc4c02", "#8c2d04"]);
var legend = d3.legend()
.translate([ width / 4 , height / 4 ])
.colors(colors)
.cb(function() { console.log("Done!"); });
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 + ")")
.call(legend);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment