Skip to content

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.

Let’s take this chart as a base.

Open in CodePen

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

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

And here’s the result:

Open in CodePen

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.

Open in CodePen
Open in CodePen