Florian Bienefelt
Florian Bienefelt

Reputation: 1578

Highcharts legend spread out to full width

Is it possible to spread legend items out over the full width of the chart, while maintaining wrapping? I'm looking for something like the flex alignment property space-between.

What I have:

enter image description here

What I want (except for only having 3 items on the first row, which is fine): enter image description here

Upvotes: 1

Views: 847

Answers (1)

morganfree
morganfree

Reputation: 12472

You can dynamically reposition legend items on load/redraw events.

Based on your fiddle, the method can be like this (for html items width must be grabbed differently)

function adjustLegend() {
  const legend = this.legend
  const legendWidth = this.chartWidth - 20

  legend.allItems.forEach((item, i, allItems) => {
    const {width, height} = item.legendGroup.getBBox()
    const itemsPerRow = i < 3 ? 3 : 2

    item.legendGroup.attr({
      translateX: (i % itemsPerRow) * (legendWidth - width) / (itemsPerRow - 1),
      translateY: Math.floor(i / 3) * (height + 5)
    })
  })
}

In chart options:

events: {
  load: adjustLegend,
  redraw: adjustLegend
}

example: https://jsfiddle.net/f6btakom/1/

Upvotes: 2

Related Questions