Public
Edited
May 26, 2022
Importers
11 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function plotLegend(
legendData = [],
{
marginTop,
marginLeft,
marginRight,
marginBottom,
fontSize,
fontFamily = "system-ui,sans-serif",
legendItemHeight,
width
} = {}
) {
// generate Plot marks based on legendData
const lData = legendData.map((lg, i) => ({
...lg,
y: i + 1
}));

const legendMarks = lData
.map((lg, i) => {
// dot and symbols
if (lg.type == "dot") {
return Plot.dot([lg], {
x: 0,
y: (d) => d.y,
dx: "7",
stroke: `${lg.stroke}`,
fill: `${lg.fill}`,
symbol: `${lg.symbol || "circle"}`
});
}
// image
if (lg.type == "image") {
return Plot.image([lg], {
x: 0,
y: (d) => d.y,
dx: "7",
src: (d) => `${d.symbol}`,
preserveAspectRatio: "xMidYMid slice"
});
}
// default to horizontal line
return Plot.ruleY([lg], {
y: (d) => d.y,
stroke: `${lg.stroke}`,
strokeDasharray: `${lg.strokeDasharray}`
});
})
.concat([
// legend item text
Plot.textY(lData, {
x: 1,
y: (d) => d.y,
textAnchor: "start",
dx: "15",
text: (d) => d.text
})
]);

return Plot.plot({
marginTop: marginTop || 0,
marginLeft: marginLeft || 0,
marginRight: marginRight || 170,
marginBottom: marginBottom || 0,
height: legendData.length * (legendItemHeight || 20),
width: width || 200,
style: {
fontSize: `${fontSize || 10}px`,
fontFamily
},
y: {
type: "point"
},
x: {
domain: [0, 1],
type: "point"
},
marks: legendMarks
});
}
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