Search code examples
javascriptchartsamcharts

Generate legends for each bubble in amcharts v4


I am trying to create a bubble chart using amCharts Version 4 library. Each bubble here represent a different country having different color. Now I need to generate legends for each bubble present in the chart. I am not able to achieve the same. Can anyone help me for it.

I am using the below mentioned tutorial to create the bubble chart.

https://www.amcharts.com/demos/zoomable-bubble-chart


Solution

  • According to the official docs you could use custom data for your legend.

    chart.legend = new am4charts.Legend();
    chart.legend.data = [{
      "name": "2016",
      "fill":"#72A6B2"
    }, {
      "name": "2017",
      "fill": "#667E93"
    }, {
      "name": "2018",
      "fill": "#488BB2"
    }];
    

    To adapt this to your data and create a legend for all countries you could use the following snippet:

    chart.legend = new am4charts.Legend();
    chart.legend.data = chart.data.map(i => ({
      "name": i.title, 
      "fill": i.color
    }));
    

    To update the data on legend toggle you can add a hidden property on your data values and tell amcharts to use it to hide some bullets.

    series.dataFields.hidden = "hidden";
    

    Add the data id to the legend data and the hidden property if you want to hide some countries on init.

    chart.legend.data = chart.data.map(i => ({
      id: i.id, 
      name: i.title, 
      fill: i.color,
      visible: !i.hidden
    }));
    

    Add an click event to the legend to update the chart. Use the "up" event, because event.target.isActive is updated after the "hit" event is called.

    chart.legend.itemContainers.template.events.on("up", (event) => {
      const id = event.target.dataItem.dataContext.id;
      chart.data.find(i => i.id === id).hidden = !event.target.isActive;
      chart.validateData();
    });
    

    I created this code pen as reference.