Published
Edited
Nov 21, 2020
Importers
Insert cell
md`# Legend Utils`
Insert cell
{
return renderInfographic({
funcDrawLegend: function(svg) {
drawLegend(svg, [1, 2, 3], {});
},
showGrid: true
});
}
Insert cell
import { addDefaults } from '@nuuuwan/option-utils'
Insert cell
import { drawText, drawCircle, DEFAULT_STYLE } from '@nuuuwan/svg-utils'
Insert cell
import {
renderInfographic,
INFOGRAPHIC_PADDING,
INFOGRAPHIC_WIDTH,
INFOGRAPHIC_HEIGHT
} from '@nuuuwan/infographic-utils'
Insert cell
LEGEND_ITEM_HEIGHT = 24
Insert cell
function drawLegend(svg, legendDataList, options = {}) {
options = addDefaults(options, {
parentWidth: INFOGRAPHIC_WIDTH,
parentHeight: INFOGRAPHIC_HEIGHT,
parentPadding: INFOGRAPHIC_PADDING,
legendWidth: 200,
legendItemHeight: LEGEND_ITEM_HEIGHT,
funcDataToColor: function(data) {
return 'red';
},
funcDataToLabel: function(data) {
return data;
},
opacity: DEFAULT_STYLE.opacity
});

const nLegendDataList = legendDataList.length;
legendDataList.forEach(function(legendData, i) {
const [x, y] = [
options.parentWidth - options.legendWidth,
options.parentHeight / 2 +
(i - (nLegendDataList - 1) / 2) * LEGEND_ITEM_HEIGHT
];
const r = LEGEND_ITEM_HEIGHT / 3;
drawCircle(svg, [x, y], r, {
fill: options.funcDataToColor(legendData),
stroke: null,
opacity: options.opacity
});
drawText(svg, [x + r * 2, y], options.funcDataToLabel(legendData), {
fontSize: DEFAULT_STYLE.fontSize / 1.5,
textAnchor: 'start',
fill: 'black'
});
});
}
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