Using d3-legend to create an legend from an ordinal scale, but with a sequential color scheme. I chose this method because the categorical values imply order, as they represent values that have been pre-binned.
For this to work, the index of each value in the categories
array is divided by the array length - 1 and passed to d3.interpolateYlGnBu()
.
Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-legend/2.24.0/d3-legend.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
svg.append("g")
.attr("class", "legendOrdinal")
.attr("transform", "translate(20,20)");
var categories = ["0-2", "2.1-4", "4.1-6", "6.1-8", "8.1-10", "10.1-12", "12.1-14", "14.1-16", "16.1-18", "18.1-20", "20.1-22", "22.1-24", "24.1-26", "26.1-28", "28.1-30", ">30"];
var ordinal = d3.scaleOrdinal()
.domain(categories)
.range(categories.map((val, i) =>
d3.interpolateYlGnBu(i / (categories.length - 1))
));
var legendOrdinal = d3.legendColor()
.scale(ordinal);
svg.select(".legendOrdinal")
.call(legendOrdinal);
</script>
</body>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-scale-chromatic.v1.min.js
https://cdnjs.cloudflare.com/ajax/libs/d3-legend/2.24.0/d3-legend.js