Search code examples
amcharts4

How to highlight a column programmatically in AMCharts 4?


In AMCharts version 3, there is a demo showing how to highlight a particular column.

Is this possible using AMCharts version 4? For example, in the Simple Column demo, highlight the UK column based on its value (ie, where country = 'UK').

I tried modifying the example at https://stackoverflow.com/a/54358490/906814 but I can't get a handle on the columns in order to assess their values and then apply the active state highlight (JSFiddle).

// copied from https://stackoverflow.com/a/54358490/906814 but not working yet
var activeState = series.columns.template.states.create("active");
activeState.properties.fill = am4core.color("#E94F37");

series.columns.each(function(column) {
  alert("column") // no alert is seen
  column.setState("active");
  column.isActive = true;
})

Solution

  • There are two approaches you can take.

    1) Use an adapter on the column's fill and stroke and check the column value before modifying the color, e.g.

    series.columns.template.adapter.add('fill', function(fill, target) {  
      if (target.dataItem && target.dataItem.categoryX == "UK") {
        return "#ff0000";
      }
      return fill;
    });
    
    series.columns.template.adapter.add('stroke', function(stroke, target) {  
      if (target.dataItem && target.dataItem.categoryX == "UK") {
        return "#ff0000";
      }
      return stroke;
    })
    

    Demo

    2) Use a property field and set the stroke and fill from your data:

    chart.data = [
      // ...
      {
        "country": "UK",
        "value": 1122,
        "color": "#ff0000"
      },
      // ...
    ];
    // ...
    series.columns.template.propertyFields.fill = "color";
    series.columns.template.propertyFields.stroke = "color";
    

    Demo