legend = svg => {
let keys = [
"Existing coal",
"New solar",
"New onshore wind",
"Solar + Onshore wind"
];
svg
.append("rect")
.attr("x", -60)
.attr("y", -45)
.attr("width", 80 * 4.3)
.attr("height", 135)
.attr("class", "legend");
svg
.append("text")
.attr("x", -50)
.attr("y", -20)
.attr("font-weight", "bold")
.text("Which energy source is the cheapest?");
const g = svg
.attr("font-size", 14)
.attr("text-anchor", "start")
.selectAll("g")
.data(keys)
.join("g")
.attr(
"transform",
(d, i) => `translate(${i < 3 ? -80 : 80},${i * 30 - (i < 3 ? 0 : 90)})`
);
g.append("circle")
.attr("cx", 35)
.attr("cy", d => 12)
.attr("r", 5)
.attr("fill", d => color(keys.indexOf(d)));
g.append("text")
.attr("x", 45)
.attr("y", 12)
.attr("dy", "0.35em")
.text(d => d);
}