Individual legend item for each column

Normally on an XY Chart, Legend creates a single item for each Series. This brief tutorial will show how you can create custom legend which will show an item for each individual column in a single Column series.

Base chart

Let's take this chart as a base.

See the Pen amCharts 4: legend item for each column by amCharts team (@amcharts) on CodePen.0

It uses an adapter to color each column in a Column series with a different color.

Adding a legend

This chart contains only one Series, so if we added a Legend it would show just one item in it.

That's not what we want. So, we're going to:

  1. Create a custom legend.
  2. Populate its data automatically with the info for each column.

Creating legends with custom items is covered in "Adding custom items" section of "Legend" article. Make sure you check it out for the basics. Instead, let's focus on how we can auto-populate it.

For that we will use Serie's ready event. It kicks in when Series is fully initialized, so we know the columns we're creating legend for are already there.

What we are going to do is to iterate through columns list of the Series, and add an entry in our custom legend's data for it.

var legend = new am4charts.Legend();
legend.parent = chart.chartContainer;
legend.itemContainers.template.togglable = false;
legend.marginTop = 20;

series.events.on("ready", function(ev) {
let legenddata = [];
series.columns.each(function(column) {
legenddata.push({
name: column.dataItem.categoryX,
fill: column.fill
})
});
legend.data = legenddata;
});
var legend = new am4charts.Legend();
legend.parent = chart.chartContainer;
legend.itemContainers.template.togglable = false;
legend.marginTop = 20;

series.events.on("ready", function(ev) {
var legenddata = [];
series.columns.each(function(column) {
legenddata.push({
name: column.dataItem.categoryX,
fill: column.fill
})
});
legend.data = legenddata;
});
{
// …
"chartContainer": {
"children": [{
"type": "Legend",
"forceCreate": true,
"id": "legend",
"itemContainers": {
"togglable": false
}
}]
},
"series": [{
// …
"events": {
"ready": function(ev) {
var series = ev.target;
var legend = ev.target.map.getKey("legend");
var legenddata = [];
series.columns.each(function(column) {
legenddata.push({
name: column.dataItem.categoryX,
fill: column.fill
});
});
legend.data = legenddata;
}
}
}]
}

And here's the result:

See the Pen amCharts 4: legend item for each column by amCharts team (@amcharts) on CodePen.0

Advanced example

Now let's modify the the chart so that legend items toggle related columns as well as show tooltip on a column when rolled over a legend item.

See the Pen amCharts 4: legend item for each column (w/ legend toggling) by amCharts team (@amcharts) on CodePen.24419

RadarChart example

See the Pen amCharts 4: Individual legend item for each column (solid gauge) by amCharts team (@amcharts) on CodePen.24419