This example demonstrates use of the d3-legend library.
The color scale comes from ColorBrewer.
forked from curran's block: Using d3-legend
xxxxxxxxxx
<html>
<head>
<meta charset="utf-8">
<title>Learning to use color legend from d3.legend</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3-legend/1.1.0/d3-legend.js"></script>
<script src="colorbrewer.min.js"></script>
</head>
<body>
<svg width="960" height="500"></svg>
<script>
var svg = d3.select("svg");
// Color legend.
var colorScale = d3.scale.quantize()
.domain([ 1, 10 ])
.range(colorbrewer.Blues[9]);
var colorLegend = d3.legend.color()
.labelFormat(d3.format(".0f"))
.scale(colorScale)
.shapePadding(5)
.shapeWidth(50)
.shapeHeight(20)
.labelOffset(12);
svg.append("g")
.attr("transform", "translate(352, 60)")
.call(colorLegend);
var data = [3,8,5,2,8,9,2];
svg.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr("r", function(d,i){return d * 2.5})
.attr("cx", function(d,i){return i * 50 + 30})
.attr("cy", 100)
.attr("fill", function(d,i){return colorScale(d)});
</script>
</body>
</html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js
https://cdnjs.cloudflare.com/ajax/libs/d3-legend/1.1.0/d3-legend.js