Published
Edited
Aug 3, 2022
Insert cell
//md`# Creating Legends for Charts -- forked to create legend for my work in w210 capstone - Summer 2022`
Insert cell
discreteLegend( {labels:[
{"party":"Mean Views","primary":"#aaaaaa"},
{"party":"Followers","primary":"#d50000"},
{"party":"Sentiment Scores","primary":"#3F8428"},
],
nColumns:4})

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

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