Grouping legend items

This short tutorial will introduce two approaches that can be used to group legend items by inserting a label between its items.

Approach #1

The easiest approach is to create a legend like we would do on any chart, set its data, then insert Label elements at predefined places in legend's children list.

function insertLegendLabel(text, index) {
  let label = legend.children.insertIndex(index, am5.Label.new(root, {
    text: text,
    fontWeight: "bold",
    paddingLeft: 0
  }));
}

insertLegendLabel("Third group", 4);
insertLegendLabel("Second group", 2);
insertLegendLabel("First group", 0);
function insertLegendLabel(text, index) {
  var label = legend.children.insertIndex(index, am5.Label.new(root, {
    text: text,
    fontWeight: "bold",
    paddingLeft: 0
  }));
}

insertLegendLabel("Third group", 4);
insertLegendLabel("Second group", 2);
insertLegendLabel("First group", 0);

The downside to this approach is that we need to know specific indexes to insert labels at.

We also need to take into account that after inserting a new child (label), the indexes of the elements that go below it will shift up, hence the reversed order in the code above.

See the Pen
Grouping legend items
by amCharts team (@amcharts)
on CodePen.0

Approach #2

This approach is more sophisticated, and thus requires more steps.

First, we create a Container that will act as a placeholder for our multiple legends.

Then we create a Label and a Legend element for each group, which we then push into container's children.

let legendContainer = chart.children.unshift(am5.Container.new(root, {
  centerY: am5.p50,
  y: am5.p50,
  layout: root.verticalLayout
}));

function createLegend(heading, items) {
  let label = legendContainer.children.push(am5.Label.new(root, {
    text: heading,
    fontWeight: "bold",
    paddingLeft: 0
  }));
  
  let legend = legendContainer.children.push(
    am5.Legend.new(root, {
      layout: root.verticalLayout
    })
  );
  
  legend.data.setAll(items);
}

createLegend("First group", [series1, series2]);
createLegend("Second group", [series3, series4]);
createLegend("Third group", [series5, series6]);
var legendContainer = chart.children.unshift(am5.Container.new(root, {
  centerY: am5.p50,
  y: am5.p50,
  layout: root.verticalLayout
}));

function createLegend(heading, items) {
  var label = legendContainer.children.push(am5.Label.new(root, {
    text: heading,
    fontWeight: "bold",
    paddingLeft: 0
  }));
  
  var legend = legendContainer.children.push(
    am5.Legend.new(root, {
      layout: root.verticalLayout
    })
  );
  
  legend.data.setAll(items);
}

createLegend("First group", [series1, series2]);
createLegend("Second group", [series3, series4]);
createLegend("Third group", [series5, series6]);

This allows more control and leaves less chance for an error.

See the Pen
Grouping legend items (with labels at specific index)
by amCharts team (@amcharts)
on CodePen.0

Posted in Uncategorized