In D3.js how can I create a horizontal legend with 2 rows?
This is current JavaScript code that creates a legend:
var legendGroup = svg.append(\"g\")
const legendData = ['The United States', 'Brazil', 'India', 'China', 'United Arab Emirates'] // The names which you want to appear as legends should be inside this array.
const legend = d3.select('svg')
.append('g')
.attr('transform', 'translate(' + (margin.left + margin.right + 60) + ',' + (margin.top - 20) + ')')
.selectAll('g')
.data(legendData)
.enter()
.append('g');
legend.append('rect')
.attr('fill', (d, i) => color(d)) // const color = d3.scaleOrdinal(d3.schemeCategory10);
.attr('height', 15)
.attr('width', 15);
legend.append('text')
.attr('x', 18)
.attr('y', 10)
.attr('dy', '.15em')
.text((d, i) => d)
.style('text-anchor', 'start')
.style('font-size', 12);
// Now space the groups out after they have been appended:
const padding = 10;
legend.attr('transform', function (d, i) {
return 'translate(' + (d3.sum(legendData, function (e, j) {
if (j < i) { return legend.nodes()[j].getBBox().width; } else { return 0; }
}) + padding * i) + ',0)';
});