How to create a horizontal legend?

后端 未结 2 783

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\")         


        
2条回答
  •  粉色の甜心
    2021-01-20 16:37

    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)';
    });
    

提交回复
热议问题