Published
Edited
Nov 12, 2019
1 fork
Importers
Insert cell
md`# Creating Legends for Charts`
Insert cell
Insert cell
parties = [
{"party":"Conservative","primary":"#0087dc"},
{"party":"Labour","primary":"#d50000"},
{"party":"Nationalist (S&W)","primary":"#3F8428"},
{"party":"Liberal Democrat","primary":"#FDBB30"},
{"party":"Others","primary":"#aaaaaa"},
]
Insert cell
discreteLegend( {labels:parties,nColumns:2})

Insert cell
function discreteLegend({
labels,
nColumns=1,
colWidth=200,
keySize=32,
margin=5,
textLeft=40,
fontFamily="Helvetica Neue, sans-serif",
fontSize=16
} = {}) {

let keySpace = keySize/3;
let maxKeysPerCol = Math.ceil((labels.length+1)/nColumns)
let height = maxKeysPerCol * (keySize+keySpace+margin)
let textTop = (keySize + keySpace)/2
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.style("overflow", "visible")
.style("display", "block");

svg.append("g")
.selectAll("rect")
.data(labels)
.join("rect")
.attr("x", (d, i) => Math.floor(i/maxKeysPerCol) * (colWidth))
.attr("y", (d, i) => (i%maxKeysPerCol) * (keySize+keySpace))
.attr("width", keySize)
.attr("height", keySize)
.attr("fill", d => d.primary);
svg.append("g")
.selectAll("text")
.data(labels)
.join("text")
.attr("x", (d, i) => Math.floor(i/maxKeysPerCol) * (colWidth) + textLeft)
.attr("y", (d, i) => ((i%maxKeysPerCol) * (keySize+keySpace)) + textTop)
.attr("font-family",fontFamily)
.attr("font-size",fontSize)
.attr("fill","black")
.text(d => d.party);

return svg.node();
}

Insert cell
//

cViridisN = function (thresholds) {
return d3.range(0,1.1,1/(thresholds.length)).map(d3.interpolateViridis)
}
Insert cell
{
let t = [50, 55, 60, 65, 70, 75, 80]
return legend({
color: d3.scaleThreshold(t, cViridisN(t)),
title: "Turnout (%)"
})
}
Insert cell
Insert cell
Insert cell
d3=require('d3')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more