Skip to content

Instantly share code, notes, and snippets.

@ckhung
Last active December 28, 2015 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckhung/120676bbaaaf4c7fbec1 to your computer and use it in GitHub Desktop.
Save ckhung/120676bbaaaf4c7fbec1 to your computer and use it in GitHub Desktop.
a legend (using d3-legend.js) that dynamically changes labels
<html>
<head>
</head>
<body>
<div id="main-content">
</div>
<script type="text/javascript" src="d3.js"></script>
<script type="text/javascript" src="d3-legend.js"></script>
<script>
var canvas = d3.select('#main-content')
.append('svg')
.attr("style", "outline: 2px solid #00f;")
.attr("width", 640)
.attr("height", 480);
var capBar = canvas.append('rect')
.attr('x', 20)
.attr('y', 420)
.attr('width', 600)
.attr('height', 20)
.attr('fill', '#88f')
.on('click', function () {
rescaleLegend(Math.floor(d3.mouse(this)[0]/10)*10);
});
var legendBox = canvas.append('g')
.attr('id', 'color-legend')
.attr('transform', 'translate(20,20)');
var legendPainter = d3.legend.color()
.scale(createScale(200))
.cells(11)
.title('a legend with dynamic cap')
legendPainter(legendBox);
function rescaleLegend(cap) {
console.log(cap);
var legendBox = canvas.select('#color-legend');
// this does not work
// legendPainter.scale(createScale(cap));
// this works
// legendBox.selectAll('.label').transition().text(function (d, i) {
// return d3.format('.1f')(cap * i / 10.0);
// });
// after https://github.com/susielu/d3-legend/issues/18
// we can now write this:
legendPainter.scale(createScale(cap));
legendPainter(legendBox);
}
function createScale(cap) {
return d3.scale.linear()
.range(['white', 'blue'])
.interpolate(d3.interpolateLab)
.domain([0, cap]);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment