const rectSize = 15;
const spacing = 5;
let legend = canvas.append('g').attr('class','chart-legend')
.attr('transform', `translate(${0}, ${height + 3})`);
const legendData = [
{ label: 'low', color: '#1f77b4' },
{ label: 'medium', color: '#ff7f0e' },
{ label: 'high', color: '#2ca02c' },
{ label: 'very high', color: '#2ca02c' }
];
legend.selectAll('g')
.data(legendData)
.join('g')
.attr('class', 'legend-item')
.each(function (d, i) {
const legendItem = d3.select(this);
console.log(d.label)
console.log(d.label?.length)
let labelWidth = (d.label.length * 5) + 7 + 15
var bbox = legendItem.node().getBBox()
var width = bbox.width
console.log(width)
legendItem.append('rect')
.attr('width', rectSize)
.attr('height', rectSize)
.attr('fill', d.color);
legendItem.append('text')
.attr('x', rectSize + spacing)
.attr('y', rectSize / 2)
.attr('dy', '.35em')
.attr('text-anchor', 'start')
.text(d.label)
.attr('fill', 'black');
});
const legendItems_spacing = 12
var legendLength = 0
legend.selectAll('.legend-item').each(function(d,i) {
d3.select(this).attr('transform',function() {
var bbox = d3.select(this).node().getBBox()
var width = bbox.width
let startingPosition = 0
if (i > 0) {
startingPosition = legendLength
}
legendLength += width + legendItems_spacing
return `translate(${startingPosition},0)`
})
})