Search code examples
angulartypescriptchartsamcharts

How to create a legend in amCharts with Angular?


I have an application in which complex charts are displayed. I would like to add a legend to these, but I have no idea how to do it.

Inside my component I import amcharts like this:

import { AmChartsService } from '@amcharts/amcharts3-angular';

Then I call this function:

  getCharts(id: string) {
    this.charts.forEach(chart => {
      const amChart = this.AmChartsService.makeChart(chart.id, this.chartService.getById(MyEnum.config));
    });
  }

The config I pass into the function above is defined in my chart service like this:

const charts: Chart[] = [
  { 
    id: MyEnum.config,
    data: {
      ...
      },
      valueAxes: [{
      ...
      }],
      balloon: {
      ...
      },
      chartCursor: {
      ...
      },
      legend: {
        position: 'bottom',
        bottom: 10,
        left: 15,
        width: 'auto',
        autoMargins: false,
        data: []
      },
    }
  }
];

The legend is only displayed if I remove data:[] from the config. But then only the markers of the legend are shown.

I would like a legend on the bottom of my charts with markers and labels to illustrate the meaning of the lines.


Solution

  • The data property is used for creating your own custom markers and cannot be used with auto-generated legends by default, so you need to remove the data:[] line. To add a label to the auto-generated legend markers, set your graphs' title properties to an appropriate value as it uses the title value by default:

    "graphs": [{
      "title": "graph 1",
      // ...
    },{ 
      "title": "graph 2",
      // ...
    }]