legend = g => {
const swatchSize = 16;
const spacing = 180;
const legendWidth = (swatchSize + spacing) * color.domain().length
const legendHeight = swatchSize;
const xPosition = (width - legendWidth) / 2;
const yPosition = height - legendHeight -14;
const swatch = g
.attr("transform", `translate(${xPosition},${yPosition})`)
.attr("text-anchor", "start")
.selectAll("g")
.data(color.domain().slice())
.join("g")
.attr("transform", (d, i) => `translate(${i * (swatchSize + spacing)}, 0)`);
swatch.append("rect")
.attr("width", swatchSize)
.attr("height", swatchSize)
.attr("fill", color);
swatch.append("text")
.attr("x", swatchSize + 6)
.attr("dy", "0.8em")
.text(d => d);
}