Public
Edited
Feb 6, 2023
Insert cell
Insert cell
// Create a legend generator like so:
legend = legendCircle()
.scale(
d3.scaleSqrt()
.domain([0, 500])
.range([0, 40])
)
.tickValues([15, 150, 500])
.tickFormat((d, i, e) => i === e.length - 1 ? d + " bushels of hay" : d)
.tickSize(tickSize); // defaults to 5
Insert cell
Insert cell
{
const svg = d3.create("svg")
.attr("height", 90)
.attr("width", 180 + tickSize);
// Call it on a g element
svg.append("g")
.call(legend);
return svg.node();
}
Insert cell
legendCircle = function(context){
let scale,
tickValues,
tickFormat = d => d,
tickSize = 5;
function legend(context){
let g = context.select("g");
if (!g._groups[0][0]){
g = context.append("g");
}
g.attr("transform", `translate(${[1, 1]})`);
const ticks = tickValues || scale.ticks();
const max = ticks[ticks.length - 1];
g.selectAll("circle")
.data(ticks.slice().reverse())
.enter().append("circle")
.attr("fill", "none")
.attr("stroke", "currentColor")
.attr("cx", scale(max))
.attr("cy", scale)
.attr("r", scale);
g.selectAll("line")
.data(ticks)
.enter().append("line")
.attr("stroke", "currentColor")
.attr("stroke-dasharray", "4, 2")
.attr("x1", scale(max))
.attr("x2", tickSize + scale(max) * 2)
.attr("y1", d => scale(d) * 2)
.attr("y2", d => scale(d) * 2);
g.selectAll("text")
.data(ticks)
.enter().append("text")
.attr("font-family", "'Helvetica Neue', sans-serif")
.attr("font-size", 11)
.attr("dx", 3)
.attr("dy", 4)
.attr("x", tickSize + scale(max) * 2)
.attr("y", d => scale(d) * 2)
.text(tickFormat)
.attr('text-anchor','start')
}
legend.tickSize = function(_){
return arguments.length ? (tickSize = +_, legend) : tickSize;
}
legend.scale = function(_){
return arguments.length ? (scale = _, legend) : scale;
}

legend.tickFormat = function(_){
return arguments.length ? (tickFormat = _, legend) : tickFormat;
}
legend.tickValues = function(_){
return arguments.length ? (tickValues = _, legend) : tickValues;
}
return legend;
}
Insert cell
Insert cell
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